Home >Backend Development >Python Tutorial >How Can I Save a Python Object for Later Use?
Saving an Object: Data Persistence
Problem:
You have created an object with certain attributes and want to save it for later use. How can you accomplish this?
Solution:
To save an object in Python, you can utilize the pickle module. Here's an example using this module:
import pickle class Company(object): def __init__(self, name, value): self.name = name self.value = value with open('company_data.pkl', 'wb') as outp: company1 = Company('banana', 40) pickle.dump(company1, outp, pickle.HIGHEST_PROTOCOL) company2 = Company('spam', 42) pickle.dump(company2, outp, pickle.HIGHEST_PROTOCOL)
In this example, we:
Advanced Considerations:
The above is the detailed content of How Can I Save a Python Object for Later Use?. For more information, please follow other related articles on the PHP Chinese website!