json:用于列表和字典的数据存储和传输,无法处理集合
# 把一个一个字典放文件里,再读出来
import json
dic = {'k1':'v1',
'k2':'v2'}
str_dic = json.dumps(dic)
f = open('a.txt','a')
f.write(str_dic + '\n')
f.write(str_dic + '\n')
f.write(str_dic + '\n')
f.close()
f = open('a.txt','r')
for line in f:
dic = json.loads(line)
print(dic,type(dic))
f.close()
s = {'lis':['helo','脏水'],'ruguo':'zidian',1:4444}
print(json.dumps(s,indent=4,ensure_ascii=False))
pickle:只在python使用,可以处理所有数据类型
# pickle 写入文件方式是bytes
import pickle
dic = {'k1':'v1',
'k2':'v2'}
p = pickle.dumps(dic)
print(p)
f = open('a.txt','ab')
f.write(p)
f = open('a.txt','rb')
dic = f.read()
dic = pickle.loads(dic)
print(dic)
f.close()
pickle可以连续读出pickle数据文件
import pickle
dic1 = {'k1':'v1'}
dic2 = {'k2':'v1'}
dic3 = {'k3':'v1'}
dic4 = {'k4':'v1'}
with open('a.txt','ab') as f:
pickle.dump(dic1,f)
pickle.dump(dic2,f)
pickle.dump(dic3,f)
pickle.dump(dic4,f)
with open('a.txt', 'rb') as f:
while True:
try:
dic = pickle.load(f)
print(dic)
except Exception as e:
print(e)
break