3 回答

TA贡献1797条经验 获得超4个赞
如果您不想关闭并重新打开文件,为避免出现竞争情况,可以truncate这样做:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
使用每个mVChr的注释,此功能也可能更干净,更安全with open as,即使发生错误,该注释也会关闭处理程序。
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()

TA贡献1788条经验 获得超4个赞
该fileinput模块提供了一种inline模式,用于在不使用临时文件等的情况下将更改写入正在处理的文件。该模块很好地封装了通过对象透明地跟踪文件名来循环遍历文件列表中的行的常见操作,行号等,如果您想在循环中检查它们。
import fileinput
for line in fileinput.FileInput("file",inplace=1):
if "foobar" in line:
line=line.replace("foobar","bar")
print line
添加回答
举报