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?
In general, you should always close a file after you are done using it.
Opening Files in PythonPython has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.
You need a single stream, opened for both reading and writing. NG. The combination of ReadAllText / WriteAllText will have the same problem (another process can access the file in between). A single FileStream works, though.
You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With