How to Use Pickle in Python: Save and Load Objects Easily
Use the
pickle module in Python to save objects to a file with pickle.dump() and load them back with pickle.load(). This lets you store complex data like lists or dictionaries and retrieve them later exactly as they were.Syntax
The pickle module provides two main functions for saving and loading objects:
pickle.dump(obj, file): Saves the objectobjto the open filefile.pickle.load(file): Loads and returns the object from the open filefile.
You must open the file in binary mode: 'wb' for writing and 'rb' for reading.
python
import pickle # Save an object to a file obj = {'example': 123} # Added example object to avoid NameError with open('data.pkl', 'wb') as f: pickle.dump(obj, f) # Load the object from the file with open('data.pkl', 'rb') as f: obj = pickle.load(f)
Example
This example shows how to save a Python dictionary to a file and then load it back exactly as it was.
python
import pickle # Data to save my_data = {'name': 'Alice', 'age': 30, 'scores': [85, 90, 92]} # Save data to file with open('my_data.pkl', 'wb') as file: pickle.dump(my_data, file) # Load data from file with open('my_data.pkl', 'rb') as file: loaded_data = pickle.load(file) print(loaded_data)
Output
{'name': 'Alice', 'age': 30, 'scores': [85, 90, 92]}
Common Pitfalls
Common mistakes when using pickle include:
- Not opening the file in binary mode (
'wb'or'rb'), which causes errors. - Trying to pickle objects that are not supported, like open file handles or database connections.
- Loading pickled data from untrusted sources, which can be a security risk.
Always use pickle only with trusted data and open files correctly.
python
import pickle # Wrong: opening file in text mode causes error try: with open('data.pkl', 'w') as f: pickle.dump({'a': 1}, f) except Exception as e: print('Error:', e) # Right: open file in binary mode with open('data.pkl', 'wb') as f: pickle.dump({'a': 1}, f)
Output
Error: write() argument must be str, not bytes
Quick Reference
Remember these key points when using pickle:
- Use
pickle.dump(obj, file)to save objects. - Use
pickle.load(file)to load objects. - Always open files in binary mode:
'wb'for writing,'rb'for reading. - Only unpickle data you trust to avoid security risks.
Key Takeaways
Use pickle.dump() to save Python objects to a binary file.
Use pickle.load() to read objects back from the file.
Always open files in binary mode ('wb' for writing, 'rb' for reading).
Do not unpickle data from untrusted sources to avoid security risks.
Pickle can save complex Python objects like lists and dictionaries easily.