Python: Update serialized object
<p>I am trying to perform a simple task:<br>
1. De-serialize a previously serialized object<br>
2. Updating this object<br>
3. Serializing it back for later use  </p>

<p>I tried to do it with <code>pickle</code> with no luck.<br>
I start by doing this:  </p>

<pre><code>empty_list = []
f = open('backup.p', 'wb')
pickle.dump(empty_list, f)
f.close()
</code></pre>

<p>and later:  </p>

<pre><code>f =  open('backup.p', 'rb+')
l = pickle.load(f)
l.append('string')
pickle.dump(l, f)
f.close()
</code></pre>

<p>But when I try to load again the supposedly updated list: </p>

<pre><code>f = open('backup.p', 'rb')
updated_list = pickle.load(f)
print(updated_list)  # prints [] instead of ['string']
f.close()
</code></pre>

<p>Why doesn't the second call to <code>dump()</code> overwrite the content of <code>backup.p</code>, with the new list <code>['string']</code>? Do I have to remove <code>buckup.p</code> in order to get the desired behavior?  </p>

<p>After this:</p>

<pre><code>f =  open('backup.p', 'rb+')
l = pickle.load(f)
</code></pre>

<p>you've positioned the file object <code>f</code> at a point in the file after the pickle of <code>empty_list</code>. That means when you dump another object to the file:</p>

<pre><code>pickle.dump(l, f)
</code></pre>

<p>the new pickle gets written after the first pickle. You need to avoid that, either by clearing the file before dumping the new pickle:</p>

<pre><code>f.seek(0)
f.truncate()
</code></pre>

<p>or by dumping to a new file and then replacing the original file with the new one. (You could also seek, dump, then truncate at the end to clear any trailing garbage instead of going seek, truncate, dump.)</p>

python serialization deserialization pickle