gpt4 book ai didi

python - 在 Python 中读取和覆盖文件

转载 作者:IT老高 更新时间:2023-10-28 21:08:57 24 4
gpt4 key购买 nike

目前我正在使用这个:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()

但问题是旧文件比新文件大。所以我最终得到了一个新文件,其中包含旧文件的一部分。

最佳答案

如果您不想关闭并重新打开文件,为了避免竞争条件,您可以 truncate它:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

该功能也可能是 cleaner and safer使用 open 作为上下文管理器,即使发生错误也会关闭文件处理程序!

with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()

关于python - 在 Python 中读取和覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2424000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com