我一直在尝试读取文件,然后用一些更新的数据覆盖它.
我试过这样做:
#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)
由于某种原因,它不会覆盖文件,并且它的内容保持不变.
解决方法:
在寻找前面后截断文件.这将删除所有现有数据.
>>> 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'
>>>