1

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.

user513951
  • 12,445
  • 7
  • 65
  • 82
mufty__py
  • 127
  • 1
  • 12

2 Answers2

1

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 ("the total number is {}\n".format(s))
    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.

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
0

You can create a contextmanager:

import contextlib
@contextlib.contextmanager
def post_results(total_f, resu):
  with open(total_f ,'r') as f:
    content = f.read()
    count = content.count("FFFF")
  yield count
  with open(total_f, 'w') as f:
    s= len(resu)
    f.write ("the total number is {}\n".format(s))
    f.write('\n'.join(map(str, resu)))

with post_results('filename.txt', 'string_val') as f:
  print(f)

contextmanager creates a enter and exit sequence which enables the function to automatically perform the desired final sequence of execution. In this case, count needs to be garnered and printed and after, the value stored in count needs to be written to total_f.

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 2
    While I really love the idea of jumping to creating to a context manager, I mean Python is about creating classes, it seems overpower when the 'r+' mode exists. – Olivier Melançon Feb 17 '18 at 03:38
  • @Ajax1234, the "total_f" is only in existent after its written. I am writing a file to total_f from a list, now i need to get something from the file i wrote – mufty__py Feb 17 '18 at 03:42