Primer Python built-in module - sequencing module (JSON module, pickle module)

Primer Python built-in module - sequencing module (JSON module, pickle module)

1, the sequence of

Such sequences Python module in three ways:

json module:

A data follow a different language format conversion, i.e. a special strings of different languages ​​are used. (Such as a Python list [1, 2, 3] using a special character string is converted into json, and then sent to the developer php encoded into bytes, the developer can php decoded into a particular string, and then in the reverse Solutions to the source array (list): [1, 2, 3])

json serialization support only part of the data structure Python: dict, list, tuple, str, int, float, True, False, None

pickle module:

A data format conversion can only be followed in the Python language, it can only be used in the python language.

Python support all data types include object instance.

shelve module: dictionary-like mode of operation to operate particular string.

Sequence of essentially converting a data structure (such as dictionaries, lists), etc. as a particular sequence (string or bytes) of the process is called serialization.

(1) a sequence of module is to be converted into a common data structure of a particular sequence, and this sequence may also be a special anti-back solutions.

(2) The main purpose:

<1> to read and write data files

<2> data transmission network

(3) json module

<1> json module data structure is converted to meet the conditions of particular string, and may be restored back to deserialize

<2> can be a sequence of data types: dictionary, a list, a tuple

4 Group 2

for network transmission dumps loads ----
dump load ---- for file storage

1> dumps、loads

[1] converted into a dictionary string type
import json
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = json.dumps(dic)  #序列化:将一个字典转换成一个字符串
print(type(str_dic),str_dic)  #<class 'str'> {"k3": "v3", "k1": "v1", "k2": "v2"}
#注意,json转换完的字符串类型的字典中的字符串是由""表示的
[2] Converts a string into a dictionary type dictionary type
import json
dic2 = json.loads(str_dic)  #反序列化:将一个字符串格式的字典转换成一个字典
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
print(type(dic2),dic2)  #<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
[3] also supports the type of list
list_dic = [1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]
str_dic = json.dumps(list_dic) #也可以处理嵌套的数据类型 
print(type(str_dic),str_dic) #<class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
list_dic2 = json.loads(str_dic)
print(type(list_dic2),list_dic2) #<class 'list'> [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]

2> dump、load

[1] object into a string write them to a file
import json
f = open('json_file.json','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close()
# json文件也是文件,就是专门存储json字符串的文件。
[2] to convert the file into a string type of dictionary dictionary
import json
f = open('json_file.json')
dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)
Other Parameters

ensure_ascii: When it is True, when all non-ASCII characters appear as \ uXXXX sequence, just when the dump will ensure_ascii set to False, then credited the json Chinese to display properly.

separators: Separator, actually (item_separator, dict_separator) a tuple, the default is the (:) ,,; between which is represented by the dictionary keys "," separated by between KEY and the value ":" separated.

sort_keys: The value of data sorted according to the keys.

json sequence of stored data to a plurality of the same file

Json serialization for storing a plurality of data files is a problem, a default file can store a json json data, it can be solved, illustrated:

对于json 存储多个数据到文件中
dic1 = {'name':'oldboy1'}
dic2 = {'name':'oldboy2'}
dic3 = {'name':'oldboy3'}
f = open('序列化',encoding='utf-8',mode='a')
json.dump(dic1,f)
json.dump(dic2,f)
json.dump(dic3,f)
f.close()

f = open('序列化',encoding='utf-8')
ret = json.load(f)
ret1 = json.load(f)
ret2 = json.load(f)
print(ret)

Code above will get an error, the solution:

dic1 = {'name':'oldboy1'}
dic2 = {'name':'oldboy2'}
dic3 = {'name':'oldboy3'}
f = open('序列化',encoding='utf-8',mode='a')
str1 = json.dumps(dic1)
f.write(str1+'\n')
str2 = json.dumps(dic2)
f.write(str2+'\n')
str3 = json.dumps(dic3)
f.write(str3+'\n')
f.close()

f = open('序列化',encoding='utf-8')
for line in f:
    print(json.loads(line))

(4) pickle module

<1> pickle module is Python all data structures and the like and the object type is converted into bytes, then the reduction may go back to deserialize

<2> have only Python, Python sequence almost all data types, functions can not be anonymous sequence

And the use of json almost almost as well as two pairs of four methods.

for network transmission dumps loads ----
dump load ---- for file storage

1> dumps、loads

import pickle
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic)  # bytes类型

dic2 = pickle.loads(str_dic)
print(dic2)    #字典
# 还可以序列化对象
import pickle
def func():
    print(666)

ret = pickle.dumps(func)
print(ret,type(ret))  # b'\x80\x03c__main__\nfunc\nq\x00.' <class 'bytes'>
f1 = pickle.loads(ret)  # f1得到 func函数的内存地址
f1()  # 执行func函数

2> dump、load

dic = {(1,2):'oldboy',1:True,'set':{1,2,3}}
f = open('pick序列化',mode='wb')
pickle.dump(dic,f)
f.close()
with open('pick序列化',mode='wb') as f1:
    pickle.dump(dic,f1)

pickle sequence of stored data into a plurality of file

dic1 = {'name':'oldboy1'}
dic2 = {'name':'oldboy2'}
dic3 = {'name':'oldboy3'}

f = open('pick多数据',mode='wb')
pickle.dump(dic1,f)
pickle.dump(dic2,f)
pickle.dump(dic3,f)
f.close()

f = open('pick多数据',mode='rb')
while True:
    try:
        print(pickle.load(f))
    except EOFError:
        break
f.close()

Since writing a pickle file written context

class MyPickle:
    def __init__(self,path,mode='load'):
        self.path = path
        self.mode = 'ab' if mode=='dump' else 'rb'

    def __enter__(self):
        self.f = open(self.path, mode=self.mode)
        return self

    def dump(self,content):
        pickle.dump(content,self.f)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

    def __iter__(self):
        while True:
            try:
                yield  pickle.load(self.f)
            except EOFError:
                break


class Course:
    def __init__(self,name,price,period):
        self.name = name
        self.price = price
        self.period = period
python = Course('python',19800,'6 months')
linux = Course('linux',19800,'6 months')


with MyPickle('course_file') as p:
    for obj in p:
        print(obj.__dict__)
with MyPickle('course_file','dump') as p:
    p.dump(python)
    p.dump(linux)

with open('course_file','ab') as f:
    pickle.dump(linux,f)

with open('course_file','rb') as f:
    while True:
        try:
            obj = pickle.load(f)
            print(obj.__dict__)
        except EOFError:
            break

Guess you like

Origin www.cnblogs.com/caiyongliang/p/11506378.html