序列化写到类里

 1 import os
 2 import pickle
 3 class File_handle(object):
 4     def __init__(self,File):#判断文件是否存在
 5         self.__file = File
 6         if os.path.exists(self.__file) == False:
 7             a={}
 8             self.wirt(**a)
 9 
10     def read(self):# 读取数据
11         with open(self.__file,'rb') as f:
12             locking_r = pickle.load(f)
13             return locking_r
14 
15     def wirt(self,**args):# 保存数据
16         with open(self.__file,'wb') as f:
17             pickle.dump(args,f)
18             return 'success'
19 
20 Dict_chengji={'zhangsan':90,'lisi':99}#字典1
21 Dict_xingbie={'zhangsan':'nan','lisi':'nv'}#字典2
22 
23 P_1=File_handle('./chengji')#实例化1 文件名chengji
24 P_1.wirt(**Dict_chengji)#写入字典1
25 print (P_1.read())#读取字典1
26 
27 P_2=File_handle('./xingbie')
28 P_2.wirt(**Dict_xingbie)
29 print(P_2.read())

 

posted @ 2016-05-11 23:06  我有病我高兴  阅读(129)  评论(0编辑  收藏  举报