search
HomeBackend DevelopmentPython TutorialDetailed explanation of the use of pickle library

Detailed explanation of the use of pickle library

May 16, 2018 pm 05:42 PM
picklepythonSerialization

The use of the pickle library is mentioned in the article "Understanding what machine learning is through a simple example", and this article will further elaborate on it.

So why do we need the operations of serialization and deserialization?

  1. Easy to store. The serialization process turns textual information into a stream of binary data. In this way, the information is easily stored in the hard disk. When a file needs to be read, the data is read from the hard disk and then deserialized to obtain the original data. When the Python program is running, some data such as strings, lists, and dictionaries are obtained. I want to save them for a long time for future use, instead of simply putting them in the memory and losing the data when the power is turned off. The Pickle module in the python module collection comes in handy, it can convert objects into a format that can be transmitted or stored.

  2. The loads() function performs the same deserialization as the load() function. Instead of accepting a stream object and reading the serialized data from a file, it accepts a str object containing the serialized data and returns the object directly.

  3. Code example:

  4. [python] view plain copy
    #!/usr/bin/env python  
    # -*- coding: UTF-8 -*-  
    import cPickle as pickle   
    obj = 123, "abcdedf", ["ac", 123], {"key": "value", "key1": "value1"}  
    print obj# 输出:(123, 'abcdedf', ['ac', 123], {'key1': 'value1', 'key': 'value'})      
    # 序列化到文件    
    with open(r"d:\a.txt", "r+") as f:  
        pickle.dump(obj, f)      
    with open(r"d:\a.txt") as f:  
        print pickle.load(f)# 输出:(123, 'abcdedf', ['ac', 123], {'key1': 'value1', 'key': 'value'})    
    # 序列化到内存(字符串格式保存),然后对象可以以任何方式处理如通过网络传输    
    obj1 = pickle.dumps(obj)  
    print type(obj1)# 输出:<type &#39;str&#39;>    
    print obj1# 输出:python专用的存储格式    
      
    obj2 = pickle.loads(obj1)  
    print type(obj2)# 输出:<type &#39;tuple&#39;>    
    print obj2# 输出:(123, &#39;abcdedf&#39;, [&#39;ac&#39;, 123], {&#39;key1&#39;: &#39;value1&#39;, &#39;key&#39;: &#39;value&#39;})

2. Easy to transmit. When two processes communicate remotely, they can send various types of data to each other. No matter what type of data it is, it is transmitted over the network in the form of a binary sequence. The sender needs to convert this object into a byte sequence before it can be transmitted on the network; the receiver needs to restore the byte sequence into an object.

  • Understand what machine learning is through a simple example

pickle is a standard module of the python language. The pickle library is included after installing python. No need to install it separately.
The pickle module implements basic data serialization and deserialization. Through the serialization operation of the pickle module, we can save the object information running in the program to a file and store it permanently; through the deserialization operation of the pickle module, we can create the object saved by the last program from the file.
In the official introduction, the English description of the serialization operation has several words, such as "serializing", "pickling", "serialization", "marshalling" or "flattening", etc., they all represent serialization mean. Correspondingly, there are many English words for deserialization operations, such as "de-serializing", "unpickling", "deserailization", etc. To avoid confusion, generally use "pickling"/"unpickling", or "serialization"/"deserailization".
pickle The module is serialized in binary form and saved to a file (the suffix of the saved file is ".pkl"), and cannot be opened directly for preview. Another serialization standard module of python, json, is human-readable and can be opened and viewed directly (for example, viewed in notepad++).

The pickle module has two main types of interfaces, namely serialization and deserialization.

is often used in this way:

[python] view plain copy
import cPickle as pickle  
pickle.dump(obj,f)  
pickle.dumps(obj,f)  
pickle.load(f)  
pickle.loads(f)

The serialization operation includes:

  • pickle.dump()
  • Deserialization operations include:

  • Pickler(file, protocol).dump(obj)
  • pickle.load()

  • Unpickler(file).load()

2 序列化操作

2.1 序列化方法pickle.dump()

序列化的方法为 pickle.dump(),该方法的相关参数如下:
pickle.dump(obj, file, protocol=None,*,fix_imports=True)
该方法实现的是将序列化后的对象obj以二进制形式写入文件file中,进行保存。它的功能等同于 Pickler(file, protocol).dump(obj)
关于参数file,有一点需要注意,必须是以二进制的形式进行操作(写入)。
参考前文的案例如下:

import picklewith open(&#39;svm_model_iris.pkl&#39;, &#39;wb&#39;) as f:
    pickle.dump(svm_classifier, f)

file为’svm_model_iris.pkl’,并且以二进制的形式(’wb’)写入。

关于参数protocol,一共有5中不同的类型,即(0,1,2,3,4)。(0,1,2)对应的是python早期的版本,(3,4)则是在python3之后的版本。
此外,参数可选 pickle.HIGHEST_PROTOCOL和pickle.DEFAULT_PROTOCOL。当前,python3.5版本中,pickle.HIGHEST_PROTOCOL的值为4,pickle.DEFAULT_PROTOCOL的值为3。当protocol参数为负数时,表示选择的参数是pickle.HIGHEST_PROTOCOL。
关于参数protocol,官方的详细介绍如下:

Detailed explanation of the use of pickle library

2.2 序列化方法pickle.dumps()

pickle.dumps()方法的参数如下:
pickle.dumps(obj, protocol=None,*,fix_imports=True)
pickle.dumps()方法跟pickle.dump()方法的区别在于,pickle.dumps()方法不需要写入文件中,它是直接返回一个序列化的bytes对象。

2.3 序列化方法Pickler(file, protocol).dump(obj)

pickle模块提供了序列化的面向对象的类方法,即 class pickle.Pickler(file, protocol=None,*,fix_imports=True),Pickler类有dump()方法。
Pickler(file, protocol).dump(obj) 实现的功能跟 pickle.dump() 是一样的。
关于Pickler类的其他method,请参考官方API。

插播一条硬广:技术文章转发太多,本文来自微信公众号:“Python数据之道”(ID:PyDataRoad)。

3 反序列化操作

3.1 反序列化方法pickle.load()

序列化的方法为 pickle.load(),该方法的相关参数如下:
pickle.load(file, *,fix_imports=True, encoding=”ASCII”. errors=”strict”)
该方法实现的是将序列化的对象从文件file中读取出来。它的功能等同于 Unpickler(file).load()
关于参数file,有一点需要注意,必须是以二进制的形式进行操作(读取)。
参考前文的案例如下:

import picklewith open(&#39;svm_model_iris.pkl&#39;, &#39;rb&#39;) as f:
    model = pickle.load(f)

file为’svm_model_iris.pkl’,并且以二进制的形式(’rb’)读取。

读取的时候,参数protocol是自动选择的,load()方法中没有这个参数。

3.2 反序列化方法pickle.loads()

pickle.loads()方法的参数如下:
pickle.loads(bytes_object, *,fix_imports=True, encoding=”ASCII”. errors=”strict”)
pickle.loads()方法跟pickle.load()方法的区别在于,pickle.loads()方法是直接从bytes对象中读取序列化的信息,而非从文件中读取。

3.3 反序列化方法Unpickler(file).load()

pickle模块提供了反序列化的面向对象的类方法,即 class pickle.Unpickler(file, *,fix_imports=True, encoding="ASCII". errors="strict"),Pickler类有load()方法。
Unpickler(file).load() 实现的功能跟 pickle.load() 是一样的。
关于Unpickler类的其他method,请参考官方API。

4 那些类型可以进行序列化和反序列化操作

官方文档是这么介绍的,这里我就不进一步描述了。

Detailed explanation of the use of pickle library

写在后面

pickle模块还是比较实用的,当然,关于pickle模块,其实还有许多的信息可以去了解,想了解更多信息的童鞋,建议可以阅读下python官方的API文档(library文件)。

The above is the detailed content of Detailed explanation of the use of pickle library. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the Difference: For Loop and While Loop in PythonUnderstanding the Difference: For Loop and While Loop in PythonMay 16, 2025 am 12:17 AM

ThedifferencebetweenaforloopandawhileloopinPythonisthataforloopisusedwhenthenumberofiterationsisknowninadvance,whileawhileloopisusedwhenaconditionneedstobecheckedrepeatedlywithoutknowingthenumberofiterations.1)Forloopsareidealforiteratingoversequence

Python Loop Control: For vs While - A ComparisonPython Loop Control: For vs While - A ComparisonMay 16, 2025 am 12:16 AM

In Python, for loops are suitable for cases where the number of iterations is known, while loops are suitable for cases where the number of iterations is unknown and more control is required. 1) For loops are suitable for traversing sequences, such as lists, strings, etc., with concise and Pythonic code. 2) While loops are more appropriate when you need to control the loop according to conditions or wait for user input, but you need to pay attention to avoid infinite loops. 3) In terms of performance, the for loop is slightly faster, but the difference is usually not large. Choosing the right loop type can improve the efficiency and readability of your code.

How to Combine Two Lists in Python: 5 Easy WaysHow to Combine Two Lists in Python: 5 Easy WaysMay 16, 2025 am 12:16 AM

In Python, lists can be merged through five methods: 1) Use operators, which are simple and intuitive, suitable for small lists; 2) Use extend() method to directly modify the original list, suitable for lists that need to be updated frequently; 3) Use list analytical formulas, concise and operational on elements; 4) Use itertools.chain() function to efficient memory and suitable for large data sets; 5) Use * operators and zip() function to be suitable for scenes where elements need to be paired. Each method has its specific uses and advantages and disadvantages, and the project requirements and performance should be taken into account when choosing.

For Loop vs While Loop: Python Syntax, Use Cases & ExamplesFor Loop vs While Loop: Python Syntax, Use Cases & ExamplesMay 16, 2025 am 12:14 AM

Forloopsareusedwhenthenumberofiterationsisknown,whilewhileloopsareuseduntilaconditionismet.1)Forloopsareidealforsequenceslikelists,usingsyntaxlike'forfruitinfruits:print(fruit)'.2)Whileloopsaresuitableforunknowniterationcounts,e.g.,'whilecountdown>

Python concatenate list of listsPython concatenate list of listsMay 16, 2025 am 12:08 AM

ToconcatenatealistoflistsinPython,useextend,listcomprehensions,itertools.chain,orrecursivefunctions.1)Extendmethodisstraightforwardbutverbose.2)Listcomprehensionsareconciseandefficientforlargerdatasets.3)Itertools.chainismemory-efficientforlargedatas

Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools