【问题标题】:reading and writing to the same file simultaneously in python在python中同时读取和写入同一个文件
【发布时间】:2018-02-17 03:20:28
【问题描述】:

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

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

但它仍然无法正常工作,所以我不确定这是否正确。

【问题讨论】:

  • 运行代码时会发生什么?
  • 我有单独的结果,正在寻找一种方法将打开的 total_f 也作为读取,并将结果写入同一个文件
  • 我不知道“我有单独的结果”是什么意思。
  • 我现在将编辑问题,

标签: python file-writing


【解决方案1】:

不清楚你想从书面文件中读取什么,所以我不保证这个答案会按原样工作:它旨在展示你可能使用的工作流程:

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+' 中打开。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 虽然我真的很喜欢跳到创建上下文管理器的想法,但我的意思是 Python 是关于创建类的,当存在 'r+' 模式时它似乎压倒了。
    • @Ajax1234,“total_f”只有在写入后才存在。我正在从列表中向 total_f 写入一个文件,现在我需要从我编写的文件中获取一些东西
    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2012-12-25
    • 2011-03-09
    • 1970-01-01
    相关资源
    最近更新 更多