python - Truncating and rewriting a pickle file raises KeyError '\x00'
问题描述
I am trying to truncate pickle file after I dumped my data, but it does not seem to work like .txt file.
dic1 = {'a': 1, 'b': 2}
dic2 = {'c': 3, 'd': 4}
f = open("data.pk", "wb+")
pickle.dump(dic1, f)
f.truncate(0)
pickle.dump(dic2, f)
f.seek(0)
print pickle.load(f)
f.close()
This code raises KeyError: '\x00'. It seems like truncate(0) does not truncate file, but adds some characters like '\x00'.
Can I delete the content of the pickle file without closing and reopening it ?
解决方案
file.truncate
更改文件大小,但是,根据文档
当前文件位置没有改变。
这可以通过tell
在截断后调用文件的方法来证明。
>>> d1 = dict(a=1, b=2)
>>> d2 = dict(c=3, d=4)
>>> with open('file.bin', 'wb+') as f:
... pickle.dump(d1, f)
... f.truncate(0)
... print 'File pointer position:', f.tell()
... pickle.dump(d2, f)
... f.seek(0)
... pickle.load(f)
...
File pointer position: 30
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
File "/usr/lib64/python2.7/pickle.py", line 1384, in load
return Unpickler(file).load()
File "/usr/lib64/python2.7/pickle.py", line 864, in load
dispatch[key](self)
KeyError: '\x00'
将文件指针重置到文件的开头会产生所需的行为*
>>> with open('file.bin', 'wb+') as f:
... pickle.dump(d1, f)
... f.truncate(0)
... f.seek(0)
... pickle.dump(d2, f)
... f.seek(0)
... pickle.load(f)
...
{'c': 3, 'd': 4}
*至少,它会在我的 Linux 机器上产生所需的行为。对此问题的评论中的讨论表明这可能不适用于所有平台。