简体   繁体   中英

Read from file after write, before closing

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?

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.

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

Seek back to the start of the file before reading:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM