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.

Leave a Comment