Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing a file using two file objects in Python 3.x

f=open('filename','mode')

'w' mode will create a file and open it for writing (eventually you cannot read using the same file object) 'r+' mode will open the file for both reading and writing, however if the file was not already present it will not create a new one instead it will return error.

Now consider the scenario... I want to create a file and want to open it both for reading and writing..

Here is one way of doing it and it does works...

f = open('filename', 'w')
f.close()
f = open('filename', 'r+')

I tried another different way..

>>> f1 = open('filename','w')
>>> f2 = open('filename', 'r')
>>> f1.write('test string')
11
>>> f2.read()
''
>>> f1.close()
>>> f2.read()
'test string'

Ya it didn't work the way I expected (similar to pipes)

my question is

does f2.read() function tries to read directly from the disk or from the already available buffer cache of the file?

when will the updated file written back to the disk? it is evident that f1.close() will update the file in the disk from the memory buffers. but is there a way of forcing the disk write manually?

so it would work as follows

f1.write('test string')
#force disk write
f2.read('test string') #now it should read correct data
like image 968
ParokshaX Avatar asked Jun 07 '26 23:06

ParokshaX


2 Answers

You can open a file for reading and writing with 'open(filename, "w+")':

>>> f = open('hello.txt', 'w+')
>>> f.write('hello world\n')
12
>>> f.seek(0)
0
>>> f.read()
'hello world\n'
>>> 

The call to 'seek' is needed because the file object has a single "current position" for both reading and writing, the calls to seek resets the current file position to the start of the file to make it possible to read what you just wrote.

Note that you'll can overwrite existing data when you write again, unless you seek back to the end of the file. If you only want to append data to the file you can use mode "a+" instead of "w+".

like image 198
Ronald Oussoren Avatar answered Jun 09 '26 13:06

Ronald Oussoren


The file data can be flushed without ever closing by using f.flush()

now the pipe like behavior I wanted can be implemented as follow

>>> f1 = open('filename','w')
>>> f2 = open('filename', 'r')
>>> f1.write('test string')
11
>>> f1.flush()
>>> f2.read()
'test string'

still my other two questions are unanswered..

does f2.read() function tries to read directly from the disk or from the already available buffer cache of the file?

when will the updated file written back to the disk?

I will find it soon...

like image 39
ParokshaX Avatar answered Jun 09 '26 11:06

ParokshaX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!