Home > Article > Backend Development > This article will help you understand the pickle module in Python
The persistence module: is to make data persist.
The pickle module is a Python-specific persistence module that can persist various data including custom classes, and is more suitable for the storage of complex data in Python itself.
However, the persisted string is not readable and can only be used in the Python environment and cannot be used for data exchange with other languages.
Save Python objects directly into a file, without converting them into strings first and then saving them, and without using underlying file access operations, writing them directly into a binary file. The pickle module will create a binary format specific to the Python language. It does not require the user to consider any file details. It will help you complete the reading and writing object operations. Using pickle saves a lot of lines of code than opening a file, converting the data format, and writing.
The dumps() and loads() operations in pickle are bytes type, while using dump() and lload() When reading and writing files, use rb or wb mode, which means only receiving bytes type data.
Convert and save Python data to a pickle format file.
with open('data.pickle', 'wb') as f: pickle.dump(data, f)
Open the data file saved above with a text editor, and you will find that it is all unreadable encoding.
operation result :
将Python数据转换为pickle格式的bytes字串。
import pickle dic = {"k1":"v1","k2":123} s = pickle.dumps(dic) print(s)
运行结果:
3. pickle.load(file)
从pickle格式的文件中读取数据并转换为Python的类型。
with open('data.pickle', 'rb') as f: data = pickle.load(f)
将pickle格式的bytes字串转换为Python的类型。
import pickle dic = {"k1":"v1","k2":123} s = pickle.dumps(dic) dic2 = pickle.loads(s) print(dic2)
运行结果:
import pickle with open('data.pickle', 'rb') as f: data = pickle.load(f)
.picklle 格式的文件,用记事本打开是乱码。
运行结果:
Pickle可以持久化Python的自定义数据类型,但是在反持久化的时候,必须能够读取到类的定义。
import pickle class Person: def __init__(self, n, a): self.name = n self.age = a def show(self): print(self.name+"_"+str(self.age)) aa = Person("张三", 20) aa.show() f = open('2.txt', 'wb') pickle.dump(aa, f) f.close() # del Person # 注意这行被注释了 f = open('2.txt', 'rb') bb = pickle.load(f) f.close() bb.show()
运行结果:
If you uncomment the line del Person
, the Person class is deleted in the code Definition, then an error will occur in the subsequent load()
method.
This article mainly introduces Python In the pickle module, the main methods in the module are introduced in detail.
The above is the detailed content of This article will help you understand the pickle module in Python. For more information, please follow other related articles on the PHP Chinese website!