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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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
Method 3
Seek back to the start of the file before reading:
f.seek(0) print f.read()
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0