pickle – putting more than 1 object in a file? [duplicate]

If you pass the filehandle directly into pickle you can get the result you want. import pickle # write a file f = open(“example”, “w”) pickle.dump([“hello”, “world”], f) pickle.dump([2, 3], f) f.close() f = open(“example”, “r”) value1 = pickle.load(f) value2 = pickle.load(f) f.close() pickle.dump will append to the end of the file, so you can … Read more

ValueError: insecure string pickle

“are much more likely than a never-observed bug in Python itself in a functionality that’s used billions of times a day all over the world”: it always amazes me how cross people get in these forums. One easy way to get this problem is by forgetting to close the stream that you’re using for dumping … Read more

How to pickle a namedtuple instance correctly

Create the named tuple outside of the function: from collections import namedtuple import pickle P = namedtuple(“P”, “one two three four”) def pickle_test(): my_list = [] abe = P(“abraham”, “lincoln”, “vampire”, “hunter”) my_list.append(abe) with open(‘abe.pickle’, ‘wb’) as f: pickle.dump(abe, f) pickle_test() Now pickle can find it; it is a module global now. When unpickling, all … Read more

Simple example of use of __setstate__ and __getstate__

Here’s a very simple example for Python that should supplement the pickle docs. class Foo(object): def __init__(self, val=2): self.val = val def __getstate__(self): print(“I’m being pickled”) self.val *= 2 return self.__dict__ def __setstate__(self, d): print(“I’m being unpickled with these values: ” + repr(d)) self.__dict__ = d self.val *= 3 import pickle f = Foo() f_data … Read more