Reading from a file after writing, before closing

I am trying to read from an initially empty file after writing before closing it. Is this possible in Python?

some_data = "this is a string"

with open("outfile1.txt", 'r+') as f:
    print "Writing ..."
    f.write(some_data)
    f.flush()
    print "File contents:"
    print f.read()

print "Again ..."
print open("outfile1.txt", 'r').read()

Flushing with help f.flush()does not seem to work, since the latter print f.read()does not print anything.

Is there a way to read the "current data" from a file other than reopening it?

+4
source share
3 answers

You need to reset the index of the file object to the first position, usig seek():

some_data = "this is a string"

with open("outfile1.txt", 'r+') as f:
    print "Writing ..."
    f.write(some_data)
    f.flush()
    // "rewind" the fd to the first position
    f.seek(0)
    print "File contents :"
    print f.read()

which will make the file readable from it

+5
source

File objects track the current position in the file. You can get it using f.tell()and install it using f.seek(position).

, f.seek(0).

http://docs.python.org/2/library/stdtypes.html#file.seek

+3

Go back to the beginning of the file before reading:

f.seek(0)
print f.read()
+2
source

Source: https://habr.com/ru/post/1529651/


All Articles