11
votes

I'm trying to read from an originally empty file, after a write, before closing it. Is this possible in Python?

with open("outfile1.txt", 'r+') as f:
    f.write("foobar")
    f.flush()
    print("File contents:", f.read())

Flushing with f.flush() doesn't seem to work, as the final f.read() still returns nothing.

Is there any way to read the "foobar" from the file besides re-opening it?

3

3 Answers

12
votes

You need to reset the file object's index to the first position, using seek():

with open("outfile1.txt", 'r+') as f:
    f.write("foobar")
    f.flush()

    # "reset" fd to the beginning of the file
    f.seek(0)
    print("File contents:", f.read())

which will make the file available for reading from it.

3
votes

File objects keep track of current position in the file. You can get it with f.tell() and set it with f.seek(position).

To start reading from the beginning again, you have to set the position to the beginning with f.seek(0).

http://docs.python.org/2/library/stdtypes.html#file.seek

2
votes

Seek back to the start of the file before reading:

f.seek(0)
print f.read()