Read from file after write, before closing

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.

Leave a Comment