Read from file after write, before closing

Seek back to the start of the file before reading:

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

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


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.

Tags:

Python

File