阅读并覆盖Python中的文件 [英] Read and overwrite a file in Python
本文介绍了阅读并覆盖Python中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我使用的是:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
但问题是旧文件大于新文件。所以我最终得到一个新文件,其中有一部分旧文件。
But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.
推荐答案
如果你不想关闭并重新打开该文件,以避免竞争条件,您可以 truncate
它:
If you don't want to close and reopen the file, to avoid race conditions, you could truncate
it:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
功能也可能是更清洁和更安全的,使用打开为
每mVChr的注释,即使发生错误也将关闭处理程序。
The functionality may also be cleaner and safer using with open as
per mVChr's comment, which is will close the handler, even if an error occurs.
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
这篇关于阅读并覆盖Python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文