pickle() and cPickle('s module) are equivalent to java's serialization and deserialization operations.
It is often used in the following way:
import pickle (obj,f) (obj,f) (f) (f)
With the pickle module you can save Python objects directly to a file without converting them to strings or using underlying file access operations to write them to a binary file. The pickle module creates a python language-specific binary format, so you don't have to think about any of the details of the file, and it will do the read/write-only operations for you cleanly, the only thing you need is a legal file handle.
The two main functions in the pickle module are dump() and load():
The dump() function accepts a file handle and a data object as arguments and saves the data object in a specific format to the given file. When we use the load() function to retrieve saved objects from a file, pickle knows how to restore those objects to their original format.
dumps()
Function execution anddump()
function the same serialization. Instead of accepting stream objects and saving the serialized data to a disk file, this function simply returns the serialized data.
loads() function performs the same deserialization as the load() function. Instead of accepting a stream object and go to the file to read the serialized data, it accepts the str object containing the serialized data, the object returned directly.
Example:
# -*- coding:utf-8 -*- import pickle obj = 123, "abcdef", ["ac", 123], {"key": "value", "key1": "value1"} print(obj) # Serialize to file with open(r"F:\pycodes\ML\", "wb") as f: (obj, f) with open(r"F:\\pycodes\\ML\\", "rb") as f: print((f))# Output: (123, 'abcdef', ['ac', 123], {'key': 'value', 'key1': 'value1'}) # Serialized into memory (saved in string format), the object can then be handled in any way such as via network transfer obj1 = (obj) print(type(obj1))# Output <class 'bytes' > print(obj1)# Output: python-specific storage format b'\x80\x03(K{X\x06\x00\x00\x00abcdefq\x00]q\x01(X\x02\x00\x00\x00acq\x02K{e}q\x03(X\x03\x00\x00\x00\x00keyq\x04X\x05\ x00\x00\x00valueq\x05X\x04\x00\x00\x00\x00key1q\x06X\x06\x00\x00\x00\x00\x00value1q\x07utq\x08.' obj2 = (obj1) print(type(obj2))# Output: <class 'tuple'> print(obj2) # exports:(123, 'abcdef', ['ac', 123], {'key': 'value', 'key1': 'value1'})
summarize
The above is a small introduction to the Python3 pickle module usage, I hope to help you, if you have any questions please leave me a message, I will promptly reply to you. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!