Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from file after write, before closing

Tags:

python

file

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?

like image 869
peonicles Avatar asked Mar 02 '14 13:03

peonicles


People also ask

Is it mandatory to close a file while reading from the file?

In general, you should always close a file after you are done using it.

How do you read a file after writing in Python?

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.

Can a file be read and written at the same time?

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.

Is it mandatory to close the file in Python?

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.


2 Answers

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.

like image 127
zmo Avatar answered Sep 21 '22 08:09

zmo


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

like image 41
Pavel Anossov Avatar answered Sep 19 '22 08:09

Pavel Anossov