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.
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.
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