在 Python 中读取和覆盖文件
目前我正在使用这个:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
但问题是旧文件比新文件大。所以我最终得到一个新文件,其末尾有旧文件的一部分。
Currently I'm using this:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您不想关闭并重新打开文件,为了避免竞争条件,您可以
截断
它:该功能也可能更干净、更安全 使用
open
作为上下文管理器,即使发生错误,这也会关闭文件处理程序!If you don't want to close and reopen the file, to avoid race conditions, you could
truncate
it:The functionality will likely also be cleaner and safer using
open
as a context manager, which will close the file handler, even if an error occurs!fileinput
模块有一个inplace< /code> 模式,用于在不使用临时文件等的情况下将更改写入正在处理的文件。该模块很好地封装了通过透明地跟踪文件名、行的对象循环遍历文件列表中的行的常见操作如果您想在循环内检查它们,请使用数字等。
The
fileinput
module has aninplace
mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.在
text = re.sub('foobar', 'bar', text)
之后关闭文件,重新打开它进行写入(从而清除旧内容),可能会更容易和更整洁将更新后的文本写入其中。Probably it would be easier and neater to close the file after
text = re.sub('foobar', 'bar', text)
, re-open it for writing (thus clearing old contents), and write your updated text to it.我发现先读后写更容易记住。
例如:
I find it easier to remember to just read it and then write it.
For example:
对于任何想要按行读取和覆盖的人,请参阅此答案。
https://stackoverflow.com/a/71285415/11442980
To anyone who wants to read and overwrite by line, refer to this answer.
https://stackoverflow.com/a/71285415/11442980
尝试将其写入新文件..
Try writing it in a new file..
老实说,您可以看一下我构建的这个类,它执行基本的文件操作。 write 方法会覆盖并追加保留旧数据。
Honestly you can take a look at this class that I built which does basic file operations. The write method overwrites and append keeps old data.