标签:
用于序列化的两个模块
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
dumps和dump区别:
pickle.dump(info,f) #print(pickle.dumps(info)) #f.write(pickle.dumps(info))
loads和load区别:
data_from_atm=pickle.load(f) #data_from_atm=pickle.loads(f.read())
pickle(python中独有,支持所有python数据类型)
将字典转化为字符串
1 import pickle 2 f= open("user_acc.txt","wb") 3 4 info={ 5 "alex":"123", 6 "jack":"4444" 7 } 8 9 f.write(pickle.dumps(info)) 10 f.close()
将字符串转化为字典
import pickle f= open("user_acc.txt","rb") data_from_atm=pickle.loads(f.read()) print(data_from_atm)
json(是所有语言通用的,支持字典,列表,元组)
将字典转化为字符串
1 import pickle 2 import json 3 f= open("user_acc.txt","w") 4 5 info={ 6 "alex":"123", 7 "jack":"4444" 8 } 9 10 f.write(json.dumps(info)) 11 f.close()
将字符串转化为字典
1 import pickle,json 2 f= open("user_acc.txt","r") 3 4 data_from_atm=json.loads(f.read()) 5 6 print(data_from_atm)
实例:
Python学习笔记——基础篇【第五周】——json & pickle 模块
标签:
原文地址:http://www.cnblogs.com/yard/p/5515323.html