读取文件然后在 Python 中覆盖它
Reading a file and then overwriting it in Python
我一直在尝试读取一个文件,然后用一些更新的数据覆盖它。
我试过这样做:
#Created filename.txt with some data
with open('filename.txt', 'r+') as f:
data = f.read()
new_data = process(data) # data is being changed
f.seek(0)
f.write(new_data)
出于某种原因,它不会覆盖文件,文件内容保持不变。
您应该添加对 truncate
after seek
as 建议的调用。
尝试在不同的范围内读取和写入,这样代码更清晰,并且在打开文件处理程序时不进行数据处理。
data = ''
with open('filename.txt', 'r') as f:
data = f.read()
new_data = process(data)
with open('filename.txt', 'w+') as f:
f.write(new_data)
搜索到前面后截断文件。这将删除所有现有数据。
>>> open('deleteme', 'w').write('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
>>> f = open('deleteme', 'r+')
>>> f.read()
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
>>> f.seek(0)
>>> f.truncate()
>>> f.write('bbb')
>>> f.close()
>>> open('deleteme').read()
'bbb'
>>>
我一直在尝试读取一个文件,然后用一些更新的数据覆盖它。 我试过这样做:
#Created filename.txt with some data
with open('filename.txt', 'r+') as f:
data = f.read()
new_data = process(data) # data is being changed
f.seek(0)
f.write(new_data)
出于某种原因,它不会覆盖文件,文件内容保持不变。
您应该添加对 truncate
after seek
as
尝试在不同的范围内读取和写入,这样代码更清晰,并且在打开文件处理程序时不进行数据处理。
data = ''
with open('filename.txt', 'r') as f:
data = f.read()
new_data = process(data)
with open('filename.txt', 'w+') as f:
f.write(new_data)
搜索到前面后截断文件。这将删除所有现有数据。
>>> open('deleteme', 'w').write('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
>>> f = open('deleteme', 'r+')
>>> f.read()
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
>>> f.seek(0)
>>> f.truncate()
>>> f.write('bbb')
>>> f.close()
>>> open('deleteme').read()
'bbb'
>>>