1

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 ?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Ilyas
  • 11
  • 2

1 Answers1

0

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.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153