A brief introduction to the method of pickling module to package and unpackage data objects from python series
- 2020-04-02 13:42:24
- OfStack
Encapsulation is a process of converting Python data objects into byte streams. Unpacking is the reverse operation of encapsulation, which transfers bytes from byte files or byte objects to Python data objects. Do not unpack data from trusted data sources. Can encapsulate and unwrap almost any Python data object, mainly including:
None, True, False
Integers, floating point Numbers, complex Numbers
String, byte, ByteArray object
Tuples, lists, collections, dictionaries containing encapsulated objects
Functions defined at the top of a module
A built-in function defined at the top of a module
That's the class defined at the top of a module
The result of either calling/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s/s is an instance of the encapsulated class
The methods commonly used in the pickle module are:
1. Pickling. Dump (obj file, protocol = None,)
The required parameter obj represents the object to be encapsulated
The required parameter file represents the file object to be written by obj. The file must be opened in binary writable mode, i.e. "wb"
Protocol, an optional parameter, tells pickler which protocol to use. The supported protocol is 0,1,2, and 3. The default protocol is protocol 3 added to Python 3. See the documentation for further agreement details
2. Pickling. The load (file, *, fix_imports = True, encoding = "ASCII", errors = "strict")
The required parameter file must be opened in binary readable mode, that is, "rb", and everything else is optional
3. Pickle. Dumps (obj) : the encapsulated object is returned as a byte object and does not need to be written to a file
Pickle. Loads (bytes_object): reads the encapsulated object from the byte object and returns
There are three possible exceptions to the pickle module:
1. PickleError: an Exception class that occurs when packaging and unpacking, inherited from Exception
2. PicklingError: an exception that occurs when an unencapsulated object is encountered, inherited from PickleError
3. UnPicklingError: an exception in the process of unsealing an object, inherited from PickleError
Application examples of pickle:
import pickle
with open("my_profile.txt", "wb") as myprofile:
pickle.dump({"name":"AlwaysJane", "age":"20+", "sex":"female"}, myprofile)
with open("my_profile.txt", "rb") as get_myprofile:
print (pickle.load(get_myprofile))
import pickle
class Profile:
name = "AlwaysJane"
pickledclass = pickle.dumps(Profile)
print (pickledclass)
print (pickle.loads(pickledclass))
Understanding is not very thorough, I hope the gods correct mistakes...
Attach (link: https://docs.python.org/3.3/library/pickle.html)