Fix Python – Confused by python file mode “w+”


Asked By – holys

From the doc,

Modes ‘r+’, ‘w+’ and ‘a+’ open the file for updating (note that ‘w+’ truncates the file). Append ‘b’ to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the ‘b’ has no effect.

and here

w+ : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

But, how to read a file open with w+?

Now we will see solution for issue: Confused by python file mode “w+”


Let’s say you’re opening the file with a with statement like you should be. Then you’d do something like this to read from your file:

with open('somefile.txt', 'w+') as f:
    # Note that f has now been truncated to 0 bytes, so you'll only
    # be able to read data that you write after this point
    f.write('somedata\n')  # Important: return to the top of the file before reading, otherwise you'll just read an empty string
    data = # Returns 'somedata\n'

Note the — if you forget this, the call will try to read from the end of the file, and will return an empty string.

This question is answered By – rmunn

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0