shelve也是python提供给我们的序列化工具,比pickle用起来更简单一些。 shelve只提供给我们一个open方法,是用key来访问的,使用起来和字典类似。例子:保存数据
1 import shelve, datetime 2 import os 3 if os.path.isdir(os.getcwd() + r'\模块\shelve'): 4 pass 5 else: 6 os.makedirs(os.getcwd() + r'\模块\shelve') 7 F = shelve.open(os.getcwd() + r'\模块\shelve\shelve_text') 8 info = {'a': 'A', 'b': 'B', 'c': 'C'} 9 list_1 = ['abc', 1, 3, ['aa', 3.14], {4, 2.5}] 10 date = datetime.datetime.now() 11 F['info'] = info 12 F['list_1'] = list_1 13 F['date'] = date 14 F.close()
取回数据
1 import shelve 2 F = shelve.open(os.getcwd() + r'\模块\shelve\shelve_text') 3 F.get('info') 4 #datetime.datetime(2019, 7, 29, 19, 0, 51, 338663) 5 F.get('list_1') 6 #['abc', 1, 3, ['aa', 3.14], {2.5, 4}] 7 F.close()