0
0
PythonHow-ToBeginner · 3 min read

How to Load Object from File in Python Easily

To load an object from a file in Python, use the pickle module's load() function after opening the file in binary read mode with open(filename, 'rb'). This reads the saved object back into your program exactly as it was saved.
📐

Syntax

Use the pickle.load(file_object) function to read a saved object from a file. You must open the file in binary read mode 'rb' before loading.

  • open(filename, 'rb'): Opens the file for reading binary data.
  • pickle.load(file_object): Reads and returns the saved object from the file.
python
import pickle

with open('data.pkl', 'rb') as file:
    obj = pickle.load(file)
💻

Example

This example shows how to save a Python dictionary to a file and then load it back using pickle. It demonstrates that the loaded object is the same as the original.

python
import pickle

# Original object
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}

# Save object to file
with open('my_data.pkl', 'wb') as f:
    pickle.dump(my_dict, f)

# Load object from file
with open('my_data.pkl', 'rb') as f:
    loaded_dict = pickle.load(f)

print(loaded_dict)
Output
{'name': 'Alice', 'age': 30, 'city': 'Wonderland'}
⚠️

Common Pitfalls

Common mistakes when loading objects from files include:

  • Not opening the file in binary mode 'rb' for reading, which causes errors.
  • Trying to load from a file that was not saved with pickle or is corrupted.
  • Forgetting to close the file or not using with statement, which can cause resource leaks.

Always use with open(...) to handle files safely.

python
import pickle

# Wrong: opening file in text mode causes error
# with open('my_data.pkl', 'r') as f:
#     obj = pickle.load(f)  # This will raise an error

# Right way:
with open('my_data.pkl', 'rb') as f:
    obj = pickle.load(f)
📊

Quick Reference

ActionCode Example
Open file for reading binaryopen('filename.pkl', 'rb')
Load object from filepickle.load(file_object)
Open file for writing binaryopen('filename.pkl', 'wb')
Save object to filepickle.dump(obj, file_object)

Key Takeaways

Use the pickle module to load objects from files in Python.
Always open files in binary mode ('rb') when loading with pickle.
Use the with statement to safely open and close files.
Loading fails if the file was not saved with pickle or is corrupted.
pickle.load() restores the exact saved Python object.