Use Json modules and module Pickle

In the data serialization and deserialization of data is a common operation, Python provides two modules to facilitate developers to implement serialization data, i.e., the json module and pickle module. The main difference between these two modules as follows:

  • json format is a text sequence, and pickle is a binary serialization format;
  • json that we can visually read, but can not pickle;
  • json interoperable is widely used outside the Python system, specific pickle is Python;
  • By default, Python JSON only represents a subset of built-in types, custom classes not represented; but may represent a large amount of pickle Python data types.

Json module

Json is a lightweight data-interchange format, since it has a smaller amount of data transmitted, the data format easily resolved features, it is widely used in interaction between systems, data is transmitted as a data format. It comprises a plurality of common functions, as follows:

dumps () function

dumps()Python object function may be encoded into Json string. E.g:

#字典转成json字符串 加上ensure_ascii=False以后,可以识别中文, indent=4是间隔4个空格显示

import json         
d={'小明':{'sex':'男','addr':'上海','age':26},'小红':{ 'sex':'女','addr':'上海', 'age':24},}
print(json.dumps(d,ensure_ascii=False,indent=4))

#执行结果:
{
    "小明": {
        "sex": "男",
        "addr": "上海",
        "age": 26
    },
    "小红": {
        "sex": "女",
        "addr": "上海",
        "age": 24
    }
}

dump () function

dump()Python object function may be encoded into json string and automatically written to the file, the file does not need to write separately. E.g:

#字典转成json字符串,不需要写文件,自动转成的json字符串写入到‘users.json’的文件中 
import json                                                                         
d={'小明':{'sex':'男','addr':'上海','age':26},'小红':{ 'sex':'女','addr':'上海', 'age':24},}
#打开一个名字为‘users.json’的空文件
fw =open('users.json','w',encoding='utf-8')

json.dump(d,fw,ensure_ascii=False,indent=4)

loads () function

loads()Json function can be converted into a string data type Python. E.g:

#这是users.json文件中的内容
{
    "小明":{
        "sex":"男",
        "addr":"上海",
        "age":26
    },
    "小红":{
        "sex":"女",
        "addr":"上海",
        "age":24
    }
}

#!/usr/bin/python3
#把json串变成python的数据类型   
import json  
#打开‘users.json’的json文件
f =open('users.json','r',encoding='utf-8')
#读文件
res=f.read()
print(json.loads(res))

#执行结果:
{'小明': {'sex': '男', 'addr': '上海', 'age': 26}, '小红': {'sex': '女', 'addr': '上海', 'age': 24}}

load () function

load()With loads()similar functions, load()the function can be converted into json Python string data type, except that the former parameter is a file object, do not need to read the file alone. E.g:

#把json串变成python的数据类型:字典,传一个文件对象,不需要再单独读文件 
import json   
#打开文件
f =open('users.json','r',encoding='utf-8') 
print(json.load(f))

#执行结果:
{'小明': {'sex': '男', 'addr': '上海', 'age': 26}, '小红': {'sex': '女', 'addr': '上海', 'age': 24}}

Pickle module

Pickle Json module and module functions similar, comprising four functions, i.e. dump (), dumps (), loads () and Load (), the main differences are as follows:

  • Dumps and dump the difference that the former is to serialize the object, which object is serialized and saved to a file.
  • Loads and load difference is that the former is a serialized string deserialized, and the latter is serialized string read from the file and deserializing.

dumps () function

dumps()Function may convert the data string in the form of a special python language understanding only, for example:

import pickle
# dumps功能
import pickle
data = ['A', 'B', 'C','D']  
print(pickle.dumps(data))

b'\x80\x03]q\x00(X\x01\x00\x00\x00Aq\x01X\x01\x00\x00\x00Bq\x02X\x01\x00\x00\x00Cq\x03X\x01\x00\x00\x00Dq\x04e.'

dump () function

dump()Function can convert the data in the form of a special python string only know the language, and write to the file. E.g:

# dump功能
with open('test.txt', 'wb') as f:
    pickle.dump(data, f)
print('写入成功')

写入成功

loads () function

loads()Pickle function may convert the data into a data structure python. E.g:

# loads功能
msg = pickle.loads(datastr)
print(msg)

['A', 'B', 'C', 'D']

load () function

load()Function reads data from the data file, the data structures and convert the python. E.g:

# load功能
with open('test.txt', 'rb') as f:
   data = pickle.load(f)
print(data)

['A', 'B', 'C', 'D']

Guess you like

Origin www.cnblogs.com/liudemeng/p/11917964.html