1.json模块
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。Python的json
模块提供了编码(序列化)和解码(反序列化)JSON数据的功能。
常用方法
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
: 将Python对象编码成JSON字符串。json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
: 将JSON字符串解码成Python对象。json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
: 将Python对象编码成JSON字符串,并写入到文件中。json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
: 从文件中读取JSON字符串,并解码成Python对象。
#json模块
import json
#序列化dumps,dump 转为字符串
s = "qwrr"
with open("111.txt","w") as f:
json.dump(s,f)
with open("111.txt","w")as f:
w = json.dumps(s)
f.write(w)
#反序列化
with open("111.txt","r")as f:
s = json.load(f)
print(s)
with open("111.txt","r")as f:
w = f.read()
w = json.loads(w)
print(w)
2. Pickle模块
Pickle模块实现了二进制协议,可以将Python对象结构转换为字节流,也能将字节流恢复成Python对象。与JSON相比,Pickle支持Python特定的数据类型(如函数、类等),但Pickle数据通常不是跨语言可读的。
常用方法
pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None, *, default=None)
: 将Python对象编码成字节流。pickle.loads(data, *, fix_imports=True, encoding='ASCII', errors='strict', *, buffers=None)
: 将字节流解码成Python对象。pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None, *, default=None)
: 将Python对象编码成字节流并写入文件。pickle.load(file, *, fix_imports=True, encoding='ASCII', errors='strict', *, buffers=None)
: 从文件中读取字节流并解码成Python对象。
import pickle
s = "qwe"
with open("111.txt","wb") as f:
pickle.dump(s,f)
with open("111.txt","wb") as f:
w = pickle.dumps(s)
f.write(w)
with open("111.txt","rb")as f:
r = pickle.load(f)
print(r)
with open("111.txt","rb")as f:
r = f.read()
r = pickle.loads(r)
print(r)