Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading and writing to the same file simultaneously in python

Is it possible to read and write simultaneously to the same file? I have this chunk of code:

with open(total_f, 'w') as f:
    s= len(resu)
    #print s
    f.write ("the total number is {}\n".format(s))
    f.write('\n'.join(map(str, resu)))

with open(total_f ,'r') as f:
    content = f.read()
    count = content.count("FFFF")
    print count

but I need them to be together, because I want to write the result of count in total_f.

I tried to put in the read/write together like this:

with open(total_f, 'rw') as f:# i want to read and write at the same time
    s= len(resu)
    content = f.read()
    count = content.count("FFFF")  
    #print s
    f.write ("the total number is {}\n".format(s))
    f.write ("the total number is {}\n".format(count))
    f.write('\n'.join(map(str, resu)))

But it's still not working, and so I'm not sure if that's correct.

like image 832
mufty__py Avatar asked Sep 18 '25 10:09

mufty__py


1 Answers

It is not clear what do you want to read from the written file and so I do not guarantee this answer will work as is: it is intended to show the workflow that you may use:

with open(total_f, 'w+') as f:
    s = len(resu)
    # print(s)
    f.write (f"the total number is {s}\n")
    pos_before_data = f.tell()
    f.write('\n'.join(map(str, resu)))

    f.seek(pos_before_data)
    content = f.read()
    count = content.count("FFFF")
    print(count)

The key is to open the file in 'w+' mode and, if necessary, use f.tell() and f.seek() to navigate. Open in 'r+' if file already exists and you do not want to overwrite it.

like image 128
AGN Gazer Avatar answered Sep 20 '25 01:09

AGN Gazer