替换文件中的特殊字符串而不删除其他内容
replacing a special string in a file without removing the other contents
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)
我要替换的文本没有被替换。为什么?
你想做的事情有一个骗局: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)
回到文件开头 - 但如果您仍然想修改它,则 dupe 中的选项更适合实现您的目标.
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)
我要替换的文本没有被替换。为什么?
你想做的事情有一个骗局: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)
回到文件开头 - 但如果您仍然想修改它,则 dupe 中的选项更适合实现您的目标.