How to use Pickle to save and load Variables in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To use Pickle to save and load variables in Python, you can use the pickle.dump() method to write a Python object to a file, and the pickle.load() method to read the object back from the file. Here’s an example:

import pickle

# Create an object to save
my_dict = {'hello': 'world'}

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

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

# Print the loaded object
print(loaded_dict)

In this example, we create a dictionary my_dict and save it to a file called my_dict.pickle using the pickle.dump() method. We then load the object from the file using the pickle.load() method and store it in the loaded_dict variable. Finally, we print the loaded object to verify that it has been successfully loaded.

Note that while Pickle is a convenient way to save and load Python objects, it does have some security risks. Only unpickle data from trusted sources, as malicious code can be executed when unpickling untrusted data.

Tags: