为了让函数调用更加简洁方便,可以将pickle和unpickle调用封装在函数中,在函数中同时还打开文件,并将对象的序列化存储在文件中。
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 14 10:45:31 2018
filepickle.py
@author: BruceWong
"""
try:
import cPickle
except ImportError:
import pickle
def savedb(obj,filename):
file = open(filename,'wb')
pickle.dump(obj,file)
file.close()
def loaddb(filename):
file = open(filename,'rb')
obj = pickle.load(file)
file.close()
return obj
if __name__ == '__main__':
pass
调用实例:
datas = {'name':'Bruce','age':25,'high':175}
from filepickle import *
savedb(datas,'cccpickle')
loaddb('cccpickle')
Out[4]: {'age': 25, 'high': 175, 'name': 'Bruce'}