*使用pickle处理数据存储,类似于java中的serialization,是将对象转化为二进制码存入文件中,主要函数pickle.dump(obj,file),pickle.load(file)
*在每个文件加入后缀.pkl,实现逐行数据存入
*使用shelve,实现dictionary数据的隐形固态存储,具体实现方式与pickle相同
- import pickle
- dbfile=open('people-pickle','wb') #二进制写
- pickle.dump(db, dbfile)
- dbfile.close()
- dbfile=open('people-pickle','rb') #二进制读
- db=pickle.load(dbfile)
- print db
- import pickle
- for (key, record) in [('bob', bob), ('tom', tom), ('sue', sue)]:
- recfile = open(key + '.pkl', 'wb')
- pickle.dump(record, recfile)
- recfile.close()
- import pickle, glob
- for filename in glob.glob('*.pkl'): #当前文件夹中所有以.pkl为后缀的文件
- recfile = open(filename, 'rb')
- record = pickle.load(recfile)
- print(filename, '=>\n ', record)
- suefile = open('sue.pkl', 'rb')
- print(pickle.load(suefile)['name'])
- import shelve
- db = shelve.open('people-shelve')
- db['bob'] = bob
- db['sue'] = sue
- db.close()
- db = shelve.open('people-shelve')
- sue=db['sue']
- sue['name']='Susie Q' #不能直接赋值给db['sue']['name']
- db['sue']=sue
- db.close
- db = shelve.open('people-shelve')
- print db
- db.close()