深度阅读

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

作者
作者
2023年08月22日
更新时间
10.97 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。