用 shelve 模块来存数据
shelve模块是一个进行数据操作的python模块,如果和pickle,json模块对比,shelve模块用起来更简单。
随便写个要保存的变量,拿animals列表举个例子
import shelve
animals = ['cat','dog','lion']
data = shelve.open('test')
data['animal'] = animals
data.close()
首先是导入了shelve模块,之后再创建了一个animals列表。用data = shelve.open(‘test’)来读取test,如果test这个数据库不存在,就创建一个。创建之后,当前的工作目录就会出现新文件。因为shelve模块的存储方式是通过字典保存,所以shelve模块也能使用update,items这些字典的函数。data[animal] = animals把数据保存到数据库里。最后再用data.close()关闭数据库。
如果要读取数据,打开test数据库,然后读取就行了。
opendata = shelve.open('test')
print(opendata['animal'])
返回结果:['cat','dog','lion']
本作品采用《CC 协议》,转载必须注明作者和本文链接