Json & pickle序列化
1 import json
2
3
4 #将字典以字符串形式写入文件中
5 info = {'name':'gdr','age':22}
6
7 f = open("simple.txt",'w')
8 f.write(json.dumps(info))
9 f.close()
10
11 #将文件中的内容重新变为字典
12 f2 = open("simple.txt",'r')
13 data = json.loads(f2.read())
14 print(data)
15 f2.close()
########我是分割线###########
pickle提供了一个简单的持久化功能。可以将对象以文件的形式存放在磁盘上。
pickle模块只能在python中使用,python中几乎所有的数据类型(列表,字典,集合,类等)都可以用pickle来序列化,
pickle序列化后的数据,可读性差,人一般无法识别。
1 #pickle序列化
2 import pickle
3 def sayhi(name):
4 print(name)
5 return '结束'
6
7 info = {'name':'gdr',
8 'sayhi':sayhi
9 }
10
11 f = open("simple.txt",'wb')
12 f.write(pickle.dumps(info)) #等同于pickle.dump(info.f)
13 f.close()
14
15 #pickle反序列化
16
17 # def sayhi(name):
18 # print(name)
19
20 f2 = open("simple.txt",'rb')
21 data =pickle.loads(f2.read()) #等同于pickle.load(f2)
22 print(data['sayhi']('gdr'))
23 f2.close()
pickle 简单明了的例子:
1 import pickle 2 3 a = {'name': 'gdr', 'age': 20} 4 5 with open('pk.py','wb') as file: 6 pickle.dump(a,file) 7 8 with open('pk.py','rb') as file: 9 print(pickle.load(file))