【问题标题】:replacing a special string in a file without removing the other contents [duplicate]替换文件中的特殊字符串而不删除其他内容[重复]
【发布时间】:2019-04-19 10:32:56
【问题描述】:
with open ('npt.mdp','r+') as npt:
    if 'Water_and_ions' in npt.read():
        print(" I am replacing water and Ions...with only Water")
        s=npt.read()
        s= s.replace('Protein_BSS Water_and_ions', 'Protein_BSS Water')
        with open ('npt.mdp',"w") as f:
            f.write(s)

我要替换的文本没有被替换。为什么?

【问题讨论】:

    标签: python python-3.x file-handling


    【解决方案1】:

    你想做的事情有一个骗子:How to search and replace text in a file using Python?

    这就是您的方法不起作用的原因:

    您通过检查 if 'Water_and_ions' in npt.read(): 来使用您的文件流 - 之后 s=npt.read() 无法再读取任何内容,因为流已结束。

    修复:

    with open ('npt.mdp','r+') as npt:
        s = npt.read()                       # read here
        if 'Water_and_ions' in s:            # test s
            print(" I am replacing water and Ions...with only Water")
    
            s = s.replace('Protein_BSS Water_and_ions', 'Protein_BSS Water')
            with open ('npt.mdp',"w") as f:
                f.write(s)
    

    除了将文件读入变量之外,您还可以seek(0) 回到文件开始处 - 但如果您仍然想修改它,欺骗中的选项更适合用于归档您的目标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多