Saving Python Objects for Data Persistence
Question:
I have created a custom Python object and would like to save it for later use. How can I achieve this for data persistence?
Saving Objects with the Pickle Module:
The Pickle module in Python's standard library provides a convenient way to save objects for data persistence. Consider the following example with a custom object:
import pickle class Company: def __init__(self, name, value): self.name = name self.value = value company1 = Company('banana', 40)
To save this object, we can use the following code:
with open('company_data.pkl', 'wb') as outp: pickle.dump(company1, outp, pickle.HIGHEST_PROTOCOL)
This will create a pickle file containing the serialized representation of the company1 object.
Reading Saved Objects:
Once saved, the object can be deserialized and retrieved later:
with open('company_data.pkl', 'rb') as inp: company1 = pickle.load(inp)
company1 now contains the original object, with its name and value attributes intact.
Additional Considerations:
The above is the detailed content of How Can I Save and Load Custom Python Objects for Data Persistence?. For more information, please follow other related articles on the PHP Chinese website!