用于序列化的两个模块:
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"))