1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # Author:woshinidaye
4 #正常读取文件的时候,文档使用字符串的形式写进去的。
5 # a = {'name':'woshinidaye','age':22}
6 # with open('test','w+',encoding='utf-8') as f : #序列化
7 # # f.write(a) #直接写入会报错,因为a是字典,
8 # f.write(str(a))
9 #
10 # with open('test','r+',encoding='utf-8' ) as f : #反序列化
11 # # c= f.read() #直接这样执行会报错,TypeError: string indices must be integers
12 # d = eval(f.read()) # The source may be a string representing a Python expression
13 # #or a code object as returned by compile().
14 # # print(c['age'])
15 # print(d['age']) #这样就行,不过eval不是最推荐的办法,推荐使用json
16
17 '''
18 import json
19 a = {'name':'woshinidaye','age':22}
20 with open('test','w+',encoding='utf-8') as f :
21 f.write(json.dumps(a)) #序列化
22
23 with open('test','r+',encoding='utf-8') as f : #反序列化
24 test = json.loads(f.read())
25 print(test)
26 '''
27 #json只能用于简单的字体序列化,因为json会用到各种语言中,json此时作为序列化的中间商
28
29 '''
30 import pickle #可以对函数序列化,只能在python里面用,其他语言无法识别。
31 def b():
32 print('b')
33 a = {'name':'woshinidaye','age':22,'func':b}
34 with open('test','wb') as f :
35 f.write(pickle.dumps(a)) #序列化
36 #f.write(pickle.dumps(a)) = pickle.dump(a,f)
37 with open('test','rb') as f : #反序列化
38 test = pickle.loads(f.read())
39 #test = pickle.load(f)
40 print(test) #{'name': 'woshinidaye', 'age': 22, 'func': <function b at 0x00000219CFB4AC10>}
41 print('====>',test['func']())
42 test['func']()
43 '''