Usage of python pickles and shelve modules
- 2020-04-02 13:10:08
- OfStack
1. The pickle
Write: opens a file descriptor in write mode and calls pickle.dump to write the object in
dn = {'baidu':'www.baidu.com','qq':'www.qq.com','360':'www.360.cn'}
name = ['mayun','mahuateng','liyanhong']
f = open(r'C:a.txt','w')
pickle.dump(dn,f) ## Write an object
pickle.dump(name,f) ## Write another object
f.close()
Read: opens the file descriptor as read, calling pickle.load Load the object
f = open(r'C:a.txt')
pickle.load(f) ## Load an object
pickle.load(f) ## Load another object
f.close()
2. The shelve
The shelve module is simpler than the pickle module, with only an open function that returns a dictionary-like object that can be read and written
f = shelve.open(r'C:b.txt')
f ## Return empty dictionary
f['baidu'] = 'www.baidu.com'
f['qq'] = 'www.qq.com'
f['360'] = 'www.360.cn'
f ## Return a dictionary
f.close()
f = shelve.open(r'C:b.txt')
f ## Return a dictionary f