python - 替换文件中的特殊字符串而不删除其他内容
问题描述
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 搜索和替换文件中的文本?
这就是您的方法不起作用的原因:
您通过检查来消耗您的文件流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)
返回文件开始 - 但如果您无论如何都想修改它,则欺骗中的选项更适合用于归档您的目标。
推荐阅读
- libraries - 如何在 Atmel Studio 7.0 中创建依赖项?
- flutter - 在 Flutter 中的小部件前面添加“新”有什么意义?
- javascript - 隐形验证码测试
- javascript - 无法让我的 POST 请求正常工作
- r - 如何同时合并多个 csv 文件并汇总每个组的多个变量
- javascript - Discord.js 中的 awaitReactions 问题
- sql-server - SQL Server bacpac 在最新更新中本地导入失败(在线索引操作只能在 SQL Server 企业版中执行)
- reactjs - 阴影不会出现在本机反应中
- matlab - 符号代数简化器
- node.js - 制造商/描述等串行端口信息在 Windows 上不可用,但在 Linux 上可用,使用带有串行端口包的 node.js