当前位置:网站首页>About pickle module - 6 points that beginners must know
About pickle module - 6 points that beginners must know
2022-06-30 15:26:00 【Alien-Hu】
List of articles
1.pickle Related soul torture ,who、why??
(1). who it is?
- pickle Modules can only be Python Use in ,python Almost all data types in ( list , Dictionaries , aggregate , Class etc. ) Both can be used. pickle Serialization
- pickle Serialized data , Poor readability , People generally can't recognize
- Persistent storage , Objects can be stored on disk as files
- You can save the file in any format , But in general pkl,pickle,p、data Equiform . You create your own extension , for example 【.alien】 It's fine too
(2). why is it ?
- When you want to save an object 、 Dictionary time ,ini Format 、xml The format and other configuration files cannot be directly implemented , It needs to be parsed again . but pickle It can be directly parsed
- When you want to save binary files ,pickle It can also come in handy
- Pickle It's portable , Different operating systems , Whether it's mac、windows、linux All can be read pickle file
2.pickle How to use ,how to use ?
(1) Serialize operation object ------- Save to file
Serializing objects ---------------- And write the result data stream to the file object .
with open("test_pickle.pkl", "wb") as f:
# serialize , Write object to file
pickle.dump(obj, f, protocol=0)
def dump(obj, file, protocol=None):
Pickler(file, protocol).dump(obj)
class Pickler:
def __init__(self, file, protocol=None):
"""This takes a file-like object for writing a pickle data stream.
The optional protocol argument tells the pickler to use the
given protocol; supported protocols are 0, 1, 2. The default
protocol is 0, to be backwards compatible. (Protocol 0 is the
only protocol that can be written to a file opened in text
mode and read back successfully. When using a protocol higher
than 0, make sure the file is opened in binary mode, both when
pickling and unpickling.)
Protocol 1 is more efficient than protocol 0; protocol 2 is
more efficient than protocol 1.
- Serialization mode (protocol) Support [0, 1, 2] Three options , The larger the number, the higher the efficiency , It also means that the more severe the compression .
- The default is 0, You can basically see the saved object and list information , But if you choose 1、 or 2, It's basically garbled , It means that the compression ratio is very high
- Follow up screenshots , The effect of different compression ratios
(2) Deserialization operation ------- analysis pickle The file of
Deserialization operation -------------------- The process of parsing data from a file
with open("test_pickle.pkl", "rb") as f:
obj = pickle.load(f)
3. serialize ---- class (Class) Time code
import pickle
class Person(object):
def __init__(self, name, age, blog):
self.name = name
self.age = age
self.blog = blog
def do_serializing(file):
per = Person("alien", 18, "https://blog.csdn.net/chenmozhe22")
with open(file, "wb") as f:
pickle.dump(per, f, protocol=0)
def do_unserializing(file):
with open(file, "rb") as f:
obj = pickle.load(f)
print("obj type==========>{}".format(type(obj)))
print("obj value==========>{},{},{}".format(obj.name, obj.age, obj.blog))
if __name__ == "__main__":
file_path = r'F:\MyProjects\XXXXX\TestCase\pickle_file.obj'
do_serializing(file_path)
do_unserializing(file_path)
# Print as follows :
obj type==========><class '__main__.Person'>
obj value==========>alien,18,https://blog.csdn.net/chenmozhe22
4. Serialization mode (protoco) Effects of different values
protocol=0 Time compression effect :
protocol=1 Time compression effect :
5. serialize ---- list (list) Time code
import pickle
def do_serializing(file):
info_list = ["alien", 18, "https://blog.csdn.net/chenmozhe22"]
with open(file, "wb") as f:
pickle.dump(info_list, f, protocol=0)
def do_unserializing(file):
with open(file, "rb") as f:
obj = pickle.load(f)
print("obj type==========>{}".format(type(obj)))
print("obj value==========>{},{},{}".format(obj[0], obj[1], obj[2]))
if __name__ == "__main__":
file_path = r'F:\MyProjects\FT_AutoTestDemo\TestCase\pickle_file.pkl'
do_serializing(file_path)
do_unserializing(file_path)
# Print as follows :
obj type==========><type 'list'>
obj value==========>alien,18,https://blog.csdn.net/chenmozhe22
The serialization effect is as follows :
6. Decoding problem ---- chinese 、python2&python3 Incompatibility, etc
def do_unserializing(file):
with open(file, "rb") as f:
obj = pickle.load(f, encoding='iso-8859-1') # Try adding different decodes
Extended reading :
《python3 Configuration file ini Use of ---- Reading and writing 、list&dict&path Equivariant ----configparser》
《Python3 How to open a file in (With open)》
边栏推荐
- 1030 travel plan (30 points)
- B. Moamen and k-subarrays (codeforce+ binary search)
- Three types of technical debt that programmers often encounter: code, data, and architecture
- Matlab finds a prime number that is greater than a given integer and follows this integer
- Is Domain Driven Design (DDD) reliable?
- One dimensional and two dimensional array addresses
- [untitled]
- CCF image rotation (Full Score code + problem solving idea) 201503-01
- CCF call auction (full mark code + problem solving ideas + skill summary) 201412 - 3
- HD mechanical principle · classic dynamic drawing of mechanical design
猜你喜欢

Repair of incorrect deletion of win10 boot entry

4.4 string

FoxPro and I

Chapter III installation and use of jupyter

Review 2021, embrace change and live up to Shaohua

Chapter 2 installation and use of vscode editor

Preliminary study on AI noise reduction evaluation system of sound network

Technology sharing | how to quickly realize audio and video online calls

The principle of fluent 2 rendering and how to realize video rendering

Technology sharing | anyrtc service single port design
随机推荐
Complement (Niuke)
Is pioneer futures safe? What are the procedures for opening futures accounts? How to reduce the futures commission?
How should we understand the variability of architecture design?
1151 LCA in a binary tree (30 points)
Text matching - [naacl 2022] GPL
Using member variables and member functions of a class
1148 werewolf - Simple Version (20 points)
Matlab two-dimensional array example (extract data)
Why do high precision CNC machining centers have errors? You should pay attention to these four reasons!
M - smooth engineering continuation (minimum spanning tree)
Win10 one click Reset win10 to solve all system bugs without deleting any files and Applications
Summary of system stability construction practice
A. Theatre Square(codefore)
1137: encrypted medical record
Experiment of the planning group of the West University of technology -- pipeline CPU and data processing Adventure
day02
Noj1042 - electronic mouse running through maze
Matlab to find prime pairs within 100
E - highways (minimum spanning tree)
String connector