程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 tutorial: tutorial on using pickle module and JSON module

編輯:Python

One 、 What is serialization

Serialization is the process of transforming the state of an object into a format that can be maintained or transmitted . The opposite of serialization is deserialization , It turns the stream into an object . The two processes combine , Data can be stored and transferred easily .

Two 、 serialize pickle modular

pickle What is the module used for

Used to access structured data . be used for python Unique types and python The data types are converted .

pickle Types of data that can be stored

  • all python Supported native types : Boolean value , Integers , Floating point numbers , The plural , character string , byte ,None;
  • A list of any native types , Tuples , Dictionaries and collections ;
  • function , class , Class .

pickle Common methods in modules

pickle There are four functions :dumps,dump,loads,load

1.pickle.dumps(obj[, protocol])

Function functions : take obj Object serialization to string form , Not in a file ( Returns the encapsulated object as a byte object , No need to write to file ).

Parameters on :

  • obj: Want to serialize obj object .

  • protocal: If this item omits , The default is 0. If it's negative or HIGHEST_PROTOCOL, Use the highest protocol version .

# dumps function 
# dumps Convert data into only... In a special form python The string of language recognition 
import pickle
info = {

'name': 'Vivian',
'age': 20,
'height': 157
}
data = pickle.dumps(info) # dumps It turns the data into bytes form 
print(data)
# Output 
# b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x06\x00\x00\x00Vivianq\x02X\x03\x00\x00\x00ageq\x03K\x14X\x06\x00\x00\x00heightq\x04K\x9du.'

2.pickle.dump(obj, file, protocol=None,)

Function functions : take obj Object serialization is stored in the opened file in .

Parameters on :

Required parameters obj Represents the object to be encapsulated

Required parameters file Express obj File object to write ,file Must be opened in binary writable mode , namely “wb”

notes : A dictionary a = {‘name’:‘Tom’,‘age’:22}, use pickle.dump Save to local file , The structure of the stored data is a dictionary , And ordinary. file.write Writing to the file is a string .

# dump function 
# dump Convert data into only... In a special form python The string of language recognition , And write the file 
import pickle
info = {

'name': 'Vivian',
'age': 20,
'height': 157
}
with open('information.pkl', 'wb') as f:
pickle.dump(info, f)

3.pickle.loads(string)

Function functions : Deserialization . from string Read before serialization obj object ( Read the encapsulated object from the byte object , And back to ).

Parameters on :

string: File name .

# loads function 
# loads take pickle Data to python Data structure of 
import pickle
info = {

'name': 'Vivian',
'age': 20,
'height': 157
}
data1 = pickle.dumps(info)
print(data1)
data2 = pickle.loads(data1)
print(data2)
# Output 
# b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x06\x00\x00\x00Vivianq\x02X\x03\x00\x00\x00ageq\x03K\x14X\x06\x00\x00\x00heightq\x04K\x9du.'
# {'name': 'Vivian', 'age': 20, 'height': 157}

4.pickle.load(file)

Function functions :load Object deserialization , Read data from file , take file Object serialization read in .

Parameters on :

file: File name . Required parameters file Must be opened in binary readable mode , namely “rb”, Others are optional parameters .

# load function 
# load Read data from a data file , And converted to python Data structure of 
import pickle
with open('information.pkl', 'rb') as f:
print(pickle.load(f))
# Output 
# {'name': 'Vivian', 'age': 20, 'height': 157}

3、 ... and 、 Serialization module json

json What is the module used for

Used to access structured data . For strings and Python Conversion between data types .

json Types of data that can be stored

Can only support int\str\list\tuple\dict

json Common methods in modules

json There are four functions :dumps,dump,loads,load

1. Turn the dictionary into json strand

Only strings can be written in the file , But you can turn the dictionary into json strand ,json String is a string , Can be saved in a file .

# json.dumps Convert data into a string that is recognized by all programming languages in a special form 
import json
info = {

'name': 'Vivian',
'age': 20,
'height': 157
}
j_str = json.dumps(info) # Be careful json dumps The result is a string , No bytes
print(j_str)
print(type(j_str))
# Output 
# {"name": "Vivian", "age": 20, "height": 157}
# <class 'str'>
# Use .dump() Before the method , To open the file first , Write again 
with open('massage.json', 'w') as f:
json.dump(info, f)

2.json String into dictionary

''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :711312441 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
# json.loads Used to decode JSON data . This function returns Python The data type of the field 
print(json.loads(j_str))
print(type(json.loads(j_str)))
# Output 
# {'name': 'Vivian', 'age': 20, 'height': 157}
# <class 'dict'>
with open('massage.json') as f:
data = json.load(f)
print(data)
print(type(data))
# {"name": "Vivian", "age": 20, "height": 157}
# <class 'dict'>

Four 、json vs pickle

  • Json:

advantage : Cross language ( Data transfer between different languages is available json Handover )、 Small volume

shortcoming : Can only support int\str\list\tuple\dict

  • Pickle:

advantage : Specially designed for python Design , Support python All data types

shortcoming : Only in python Use in , Big storage space

5、 ... and 、load vs loads

load and loads It's all about realizing “ Deserialization ”, The difference lies in :

loads For memory objects

the Python The built-in data is serialized into strings . If you use json.dumps Serialized objects d_json=json.dumps({‘a’:1, ‘b’:2}), ad locum d_json Is a string ’{“b”: 2, “a”: 1}’

d=json.loads(d_json) #{ b": 2, "a": 1}, Use load Re deserialize to dict

load For file handle

If there is a local json file a.json Then you can d=json.load(open(‘a.json’))

Corresponding ,dump Is to serialize the built-in type into json Write to file after object


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved