Reading a plain text file in Java

ASCII is a TEXT file so you would use Readers for reading. Java also supports reading from a binary file using InputStreams. If the files being read are huge then you would want to use a BufferedReader on top of a FileReader to improve read performance. Go through this article on how to use a Reader I’d also recommend you download and read this wonderful … Read more

How do I create a file and write to it?

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling. Note that each of the code samples below will overwrite the file if it already exists Creating a text file: Creating a binary file: Java 7+ users can use the Files class to write to … Read more

deleting file if it exists; python

You’re trying to delete an open file, and the docs for os.remove() state… On Windows, attempting to remove a file that is in use causes an exception to be raised You could change the code to… …or you can replace all that with… …which will truncate the file to zero length before opening.

Correct way to write line to file?

This should be as simple as: From The Documentation: Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single ‘\n’ instead, on all platforms. Some useful reading: The with statement open() ‘a’ is for append, or use ‘w’ to write with truncation os (particularly os.linesep)

What is the difference between rw+ and r+

On Linux at least, there’s no difference as far as I can tell. Here’s a test script and its corresponding OS syscalls (using strace); tested on python 2.7.9. See http://man7.org/linux/man-pages/man2/open.2.html for more details on the file access and creation flags. It’s not accurate to say a file object opened with ‘r+’ cannot be used to truncate a file – … Read more

How to open a file using the open with statement

Python allows putting multiple open() statements in a single with. You comma-separate them. Your code would then be: And no, you don’t gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return … Read more