在不删除其他内容的情况下替换文件中的特殊字符串

时间:2019-04-19 10:32:57

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

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)

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

1 个答案:

答案 0 :(得分:0)

您想要做的事情有一个骗子: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)而不是将文件读入变量,而是回到文件开头-但是如果您仍然要对其进行修改,则复制文件中的选项更适合用于实现目标。< / p>