在python中同时读取和写入同一个文件

时间:2018-02-17 03:20:29

标签: python file-writing

是否可以同时读取和写入同一个文件?我有这段代码:

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

但我需要他们在一起,因为我想在count中写下total_f的结果。

我试图像这样一起放入读/写:

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

但它仍然无效,所以我不确定这是否正确。

2 个答案:

答案 0 :(得分:0)

您可以创建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创建 enter exit 序列,使该函数能够自动执行所需的最终执行序列。在这种情况下,count需要获取并打印,之后,count中存储的值需要写入total_f

答案 1 :(得分:0)

目前尚不清楚您希望从书面文件中读取什么内容,因此我不保证此答案将按原样运行:它旨在显示您可能使用的工作流程:

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

关键是以'w+'模式打开文件,(如有必要),使用f.tell()f.seek()进行导航。如果文件已存在且您不想覆盖,请在'r+'中打开。

相关问题