当前位置:网站首页>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)》
边栏推荐
- 1131: genetic correlation
- Experiment of the planning group of the West University of technology -- pipeline CPU and data processing Adventure
- Win10 one click Reset win10 to solve all system bugs without deleting any files and Applications
- Bucket sorting (C language)
- Matlab draws the image of the larger function value of the two functions (super simple)
- FoxPro and I
- Matlab to find prime pairs within 100
- Matlab finds a prime number that is greater than a given integer and follows this integer
- 高清机械原理 · 机械设计经典动图
- 先锋期货安全么?现在期货开户都是哪些流程?期货手续费怎么降低?
猜你喜欢

Review 2021, embrace change and live up to Shaohua

Anyrtc implements application scenarios based on webrtc

The short video and live broadcast incubation training camp with goods opens nationwide enrollment!

Teach you a learning method to quickly master knowledge

Rte2021 review of the practice and the way of AI OPS landing

NPM install --global --save --save dev differences

Shift operator (detailed)
![[matlab] 2D drawing summary](/img/de/6bb5385f440a2997dbf9cbb9a756eb.jpg)
[matlab] 2D drawing summary

Sum of CCF digits (full mark code + problem solving idea) 201512-1

Webrtc: industrial application based on Internet of things
随机推荐
A little idea about big experiment data
The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
CCF call auction (full mark code + problem solving ideas + skill summary) 201412 - 3
CCF date calculation (Full Score code + skill summary) February 2, 2015
1018 public bike Management (30 points)
[untitled]
1025 pat ranking (25 points)
Matlab two-dimensional array example (extract data)
C language \t usage
4.3 variables and assignments
Imitating freecodecamp to build a programming ability test platform
Review 2021, embrace change and live up to Shaohua
Shift operator (detailed)
Jupyter notebook basic knowledge learning
Preliminary study on AI noise reduction evaluation system of sound network
Complement (Niuke)
Basic requirements for tool use in NC machining of vertical machining center
Rte2021 review of the practice and the way of AI OPS landing
O - ACM contest and blackout (minimum spanning tree, Kruskal)
Win10 one click Reset win10 to solve all system bugs without deleting any files and Applications