json、pickle和shelve都是python中的序列化模块,序列化主要用于把其他格式的数据转为字符串,用于文件处理和网络传输。但其使用范围和限制有所区别。
json模块json常用方法如下:
import json
dic1 = {'1': 'a', '2': 'b'}
dic_str = json.dumps(dic1) # 字典到字符串
print(dic_str, type(dic_str))
str_dic = json.loads(dic_str) # 字符串到字典
print(str_dic, type(str_dic))
with open('text', 'w') as f: # 把字典写入了文件
json.dump(dic1, f)
with open('text', 'r') as f: # 把文件中的字符串读出来
print(json.load(f))
pickle模块
pickle可以处理几乎python的任何数据类型,但是序列化之后是bytes类型,因此打开或者写入文件需要用rb和wb
pickle可以连续多次dump和load
shelve模块shelve.open()和shelve.close()必须成对使用



