定义
shelve模块是一个简单的K,V将内存数据通过文件持久化的模块,可以持久化任何pickle支持的python数据格式。
唯一总要是函数open,open函数将文件名作为参数,并返回一个shelf对象,供你用来存储数据。你可以像操作不同字典那样操作它(只是键必须为字符串),操作完毕时,可调用close关闭。
示例1
import shelve
data = shelve.open('text.txt')
data['1'] = '我很迷茫'
data['2'] = '我有点害怕'
data.close()
运行结果:
Traceback (most recent call last):
File "F:/urllibxxxx/excited package/excited.py", line 586, in <module>
data = shelve.open('text.txt')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\shelve.py", line 243, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\shelve.py", line 227, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\dbm\__init__.py", line 88, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
上述bug是由于运行前已经存在text.txt文件,解决方式发是删除文件,shelve会自动生成。
示例2
import shelve,datetime
data = shelve.open('text.txt')
class test(object):
def __init__(self,n):
self.n = n
data['name'<