Serialization using Pickle
suggest changeHere is an example demonstrating the basic usage of pickle:
import pickle
class Family:
def __init__(self, names): self.sons = names
def __str__(self): return ' '.join(self.sons)
my_family = Family(['John', 'David'])
# Dumping to string
pickle_data = pickle.dumps(my_family, pickle.HIGHEST_PROTOCOL)
# Dumping to file
with open('family.p', 'wb') as pickle_file:
pickle.dump(my_family, pickle_file, pickle.HIGHEST_PROTOCOL)
# Loading from string
my_family = pickle.loads(pickle_data)
# Loading from file
with open('family.p', 'rb') as pickle_file:
my_family = pickle.load(pickle_file)
See Pickle for detailed information about Pickle.
WARNING: The official documentation for pickle makes it clear that there are no security guarantees. Don’t load data whose origin you don’t trust.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents