首页 > 解决方案 > 替换文件中的特殊字符串而不删除其他内容

问题描述

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)

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

标签: pythonpython-3.xfile-handling

解决方案


您想做的事情有一个骗局:如何使用 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)返回文件开始 - 但如果您无论如何都想修改它,则欺骗中的选项更适合用于归档您的目标。


推荐阅读