file.truncate
changes the file size, but, according to the docs
The current file position is not changed.
This can be demonstrated by calling the file's tell
method after truncation.
>>> 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'
Resetting the file pointer to the beginning of the file produces the desired behaviour*
>>> 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}
* At least, it produces the desired behaviour on my Linux machine. The discussion in the comments to this question suggests that this might not work on all platforms.