序列化模块— json模块,pickle模块,shelve模块

json模块

pickle模块

shelve模块

序列化——将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化。

# 序列化模块
    # 数据类型转化成字符串的过程就是序列化
    # 为了方便存储和网络传输
    # json
        # dumps
        # loads
        # dump  和文件有关
        # load  load不能load多次

# import json
# data = {'username':['李华','二愣子'],'sex':'male','age':16}
# json_dic2 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':'),ensure_ascii=False)
# print(json_dic2)

    # pickle
        #方法和json一样
        #dump和load的时候 文件是rb或者wb打开的
        #支持python所有的数据类型
        #序列化和反序列化需要相同的环境
    # shelve
        # open方法
        # open方法获取了一个文件句柄
        # 操作和字典类似
先来个总结

json模块


json特点:

1.只能处理简单的可序列化的对象:

  json 可以序列化的类型有  数字,字符串,列表,字典,元组也可以用json序列化,不过是转化成列表进行(load回来后也是列表)

2.json支持不同语言之间的数据交互

json提供了四个方法:dumps,loads 和 dump,load

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转换完的字符串类型的字典中的字符串是由""表示的

dic2 = json.loads(str_dic)  #反序列化:将一个字符串格式的字典转换成一个字典
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
print(type(dic2),dic2)  #<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}


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'}]
dumps和loads
import json
f = open('json_file','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close()

f = open('json_file')
dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)
dump和load
#json不支持多次载入再出,如果需要,用以下这个思路
#dumps和loads多行
l = [{'k1':'111'},{'k2':'222'},{'k3':'3333'}]
f = open('duohang','w')
for i in l:
    f.write(json.dumps(i)+'
')
f.close()
json中dumps多行
import json
#pickle可以序列化python任何数据类型,比如集合
#json 可以序列化的类型有  数字,字符串,列表,字典,元组也可以用json序列化,不过是转化成列表进行(load回来后也是列表)
info = {
    'name':'郭坤祥',
    'age':19,
    'job':'IT'
}
with open('序列化.txt','w',encoding='utf-8') as f:
    #f.write(json.dumps(info))           #整句话等价于  json.dump(info,f)
    json.dump(info,f,ensure_ascii=False)     #要写dump的时候文件里显示中文,需要加 ensure_ascii=False 这个参数

with open('序列化.txt','r',encoding='utf-8') as f2:
    # ret = json.loads(f2.read())          #整句话等价于  print(json.load(f2))
    # print(type(ret),ret)
    print(json.load(f2))

dumps和loads是在内存中操作数据,dump和load必须要有文件才可以使用
文件中的这四个方法
import json
f = open('file','w')
json.dump({'国籍':'中国'},f)
ret = json.dumps({'国籍':'中国'})
f.write(ret+'
')
json.dump({'国籍':'美国'},f,ensure_ascii=False)
ret = json.dumps({'国籍':'美国'},ensure_ascii=False)
f.write(ret+'
')
f.close()
ensure_asci
Serialize obj to a JSON formatted str.(字符串表示的json对象) 
Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key 
ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) 
If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). 
indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json 
separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。 
default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. 
sort_keys:将数据根据keys的值进行排序。 
To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
其他参数说明
import json
data = {'username':['李华','二愣子'],'sex':'male','age':16}
json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
print(json_dic2)
json格式化输出

#json一次不能读取多行,f.write(json.dumps(info)+' ') 

pickle模块


pickle和json用法一样,也提供 dumps,loads,dump,load 四个方法

但是pickle在dumps的时候,是把数据存为bytes数据类型
所以pickle在使用文件的时候用到的模式就是 wb和rb
pickle可以序列化python任何数据类型,比如集合
json 可以序列化的类型有 数字,字符串,列表,字典,元组也可以用json序列化,不过是转化成列表进行(load回来后也是列表)
pickle可以分步dump和分布load json就不行了

#pickle 分步序列
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic)  #一串二进制内容

dic2 = pickle.loads(str_dic)
print(dic2)    #字典

import time
struct_time1  = time.localtime(1000000000)
struct_time2  = time.localtime(2000000000)
f = open('pickle_file','wb')
pickle.dump(struct_time1,f)
pickle.dump(struct_time2,f)
f.close()
f = open('pickle_file','rb')
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
print(struct_time1.tm_year)
print(struct_time2.tm_year)
f.close()
pickle 分步序列

shelve模块


shelve模块是python3中新增的序列化模块,平常pickle和json已经足以应付日常需求,故shelve比较少使用。

简单用法如下:

import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
f.close()

import shelve
f1 = shelve.open('shelve_file')
existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
f1.close()
print(existing)


注意shelve有个坑,在虽然开启了只读模式,但是还是会更改对应的值
import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
#######   f['key']  = 50  #坑在这里
print(existing)

f.close()

f = shelve.open('shelve_file', flag='r')
existing2 = f['key']
f.close()
print(existing2)


import shelve
f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()

f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
# f2['key']['new_value'] = 'this was not here before'
f2.close()

 

原文地址:https://www.cnblogs.com/gkx0731/p/9608372.html