Reputation: 1637
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?
Upvotes: 13
Views: 10331
Reputation: 24812
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.
Upvotes: 14
Reputation: 280236
Seek back to the start of the file before reading:
f.seek(0)
print f.read()
Upvotes: 2
Reputation: 62868
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
Upvotes: 3