json & pickle 序列化
json
文件只能存取字符串和二进制数据,可以在存储时进行json序列化,读取时进行json反序列化
loads/dumps loads: str转化为json, dumps:json转化为str
with open('testjson.txt','w') as f:
f.write(json.dumps(a))
with open('testjson.txt','r') as b:
res = json.loads(b.read())
load/dump
with open('testjson.txt','w') as f:
json.dump(a, f)
with open('testjson.txt','r') as b:
res = json.load(b)
pickle
和json一样,但是存储的是二进制文件,仅支持python
loads/dumps
with open('testjson.txt','w') as f:
f.write(pickle.dumps(a))
with open('testjson.txt','r') as b:
res = pickle.loads(b.read())
load/dump
with open('testjson.txt','w') as f:
json.dump(a, f)
with open('testjson.txt','r') as b:
res = json.load(b)