python之json&pickle
阿新 • • 發佈:2018-08-24
print 寫入文件 com 轉換 col 技術 python nbsp pickle模塊
用於序列化的兩個模塊:
json:用於字符串和python數類型間進行轉換
oickle:用於python特有的類型和python的數據類型間進行轉換
json、pickle模塊提供四個功能:dumps、dump、loads、load
使用json&pickle將轉化成字符串寫入文件
1 import json 2 import pickle 3 4 def sayhi(name): 5 print("hello,", name) 6 7 info = { 8 "name":"guoxf", 9 "age":"18", 10 "sex":"nan", 11 "func":sayhi 12 } 13 14 info1 = { 15 "name":"guoxf", 16 "age":"18", 17 "sex":"nan", 18 # "func":sayhi 19 } 20 21 f = open("a.txt", "wb") 22 # json.dump(info1) # 兩者完全相等 json.dumps(info1) 23 pickle.dump(info, f) # 兩者完全相等 f.write(pickle.dumps(info)) 24 f.close()
使用json&pickle將文件中的字符串轉化成字典讀取
1 import json 2 import pickle 3 4 def sayhi(name): 5 print("hello,", name) 6 7 f = open("a.txt", "rb") 8 # data = json.loads(f.read()) 9 # data = pickle.loads(f.read()) 10 data = pickle.load(f) 11 print(data) 12 13 f.close() 14 15 print(data["func"]("gxf"))
python之json&pickle