What is pickling and unpickling in Python?
Pickling is the process of converting a Python object into a stream of bytes so it can be saved in a file or sent over a network. Unpickling is the reverse: reading those bytes and rebuilding the original object. Both are done with the built-in pickle module.
import pickle
data = {"name": "Robin", "marks": [90, 85]}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)
with open("data.pkl", "rb") as f:
loaded = pickle.load(f)
print(loaded)
Output:
Tutorials Class - Output Window
{'name': 'Robin', 'marks': [90, 85]}
Files must be opened in binary mode (wb and rb). Important: never unpickle data from a source you do not trust, because it can run harmful code. For data that other programs or languages also need, JSON is the safer choice.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |