目前,我正在使用此:
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()
该功能将很可能也更清洁和更安全的使用open
作为一个上下文管理器,这将关闭该文件处理程序,即使出现错误!
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
该fileinput
模块提供了一种inplace
模式,用于在不使用临时文件等的情况下将更改写入正在处理的文件中。该模块很好地封装了通过对象透明地跟踪文件名来遍历文件列表中的行的常见操作,行号等,如果您想在循环内检查它们。
from fileinput import FileInput
for line in FileInput("file", inplace=1):
line = line.replace("foobar", "bar")
print(line)
在关闭文件后text = re.sub('foobar', 'bar', text)
,重新打开文件以进行写入(从而清除旧内容),然后将更新后的文本写入其中,可能会更容易更整洁。
老实说,您可以看一下我构建的该类,它执行基本的文件操作。write方法将覆盖并追加保留旧数据。
class IO:
def read(self, filename):
toRead = open(filename, "rb")
out = toRead.read()
toRead.close()
return out
def write(self, filename, data):
toWrite = open(filename, "wb")
out = toWrite.write(data)
toWrite.close()
def append(self, filename, data):
append = self.read(filename)
self.write(filename, append+data)
我发现记住它,然后再写就容易记住了。
例如:
with open('file') as f:
data = f.read()
with open('file', 'w') as f:
f.write('hello')
尝试将其写入新文件中。
f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
本文地址:http://python.askforanswer.com/zaipythonzhongduquhefugaiwenjian.html
文章标签:file , overwrite , python
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
文章标签:file , overwrite , python
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!