shelve模块

python 专有的序列化模块 只针对文件,用来持久化任意的Python对象

感觉比pickle用起来更简单一些,它也是一个用来持久化Python对象的简单工具。当我们写程序的时候如果不想用关系数据库那么重量级的东东去存储数据,不妨可以试试用shelve。shelf也是用key来访问的,使用起来和字典类似。shelve其实用anydbm去创建DB并且管理持久化对象的。shelve只有一个open方法。

创建一个新的shelve,直接使用shelve.open()就可以创建了,可以直接存入数据。

importshelve

s= shelve.open('test_shelve.db') #打开文件

try:

s['key'] = {'int': 9, 'float': 10.0, 'string': 'happy'}#直接对文件句柄操作,就可以存入数据

finally:

s.close()

shelve的创建

如果要再次访问

importshelve

s= shelve.open('test_shelve.db')try:

existing= s['key']#取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错

finally:

s.close()print(existing)

访问shelve

dbm这个模块有个限制,它不支持多个应用同一时间往同一个DB进行写操作。所以当我们知道我们的应用如果只进行读操作,我们可以让shelve通过只读方式打开DB:

importshelve

s= shelve.open('test_shelve.db', flag='r')try:

existing= s['key']finally:

s.close()print(existing)

设置只读模式

当我们的程序试图去修改一个以只读方式打开的DB时,将会抛一个访问错误的异常。异常的具体类型取决于anydbm这个模块在创建DB时所选用的DB。

写回(Write-back)

由于shelve在默认情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。

importshelve

s= shelve.open('test_shelve.db')try:print(s['key'])

s['key']['new_value'] = 'this was not here before'

finally:

s.close()

s= shelve.open('test_shelve.db', writeback=True)try:print(s['key'])finally:

s.close()

写回writeback

上面这个例子中,由于一开始我们使用了缺省参数shelve.open()了,因此第6行修改的值即使我们s.close()也不会被保存。

所以当我们试图让shelve去自动捕获对象的变化,我们应该在打开shelf的时候将writeback设置为True。当我们将writeback这个flag设置为True以后,shelf将会将所有从DB中读取的对象存放到一个内存缓存。当我们close()打开的shelf的时候,缓存中所有的对象会被重新写入DB。

下面这个例子就能实现写入了

importshelve

s= shelve.open('test_shelve.db', writeback=True)try:print(s['key'])

s['key']['new_value'] = 'this was not here before'

finally:

s.close()

s= shelve.open('test_shelve.db', writeback=True)try:print(s['key'])finally:

s.close()

写回的正确方式

writeback方式有优点也有缺点。优点是减少了我们出错的概率,并且让对象的持久化对用户更加的透明了;但这种方式并不是所有的情况下都需要,首先,使用writeback以后,shelf在open()的时候会增加额外的内存消耗,并且当DB在close()的时候会将缓存中的每一个对象都写入到DB,这也会带来额外的等待时间。因为shelve没有办法知道缓存中哪些对象修改了,哪些对象没有修改,因此所有的对象都会被写入。

在shelve中,不能修改原有的数据结构类型,只能去覆盖原来的

importshelve

f= shelve.open('shelve_file', flag='r')#f['key']['int'] = 50 # 不能修改已有结构中的值#f['key']['new'] = 'new' # 不能在已有的结构中添加新的项

f['key'] = 'new' #但是可以覆盖原来的结构

f.close()

覆盖原来的结构

复杂的例子来一个

importtimeimportdatetimeimportshelveimporthashlib

LOGIN_TIME_OUT= 60db= shelve.open('user_shelve.db', writeback=True)defnewuser():globaldb

prompt= "login desired:"

whileTrue:

name=input(prompt)if name indb:

prompt= "name taken, try another:"

continue

elif len(name) ==0:

prompt= "name should not be empty, try another:"

continue

else:breakpwd= input("password:")

db[name]= {"password": hashlib.md5(pwd), "last_login_time": time.time()}#print '-->', db

defolduser():globaldb

name= input("login:")

pwd= input("password:")try:

password= db.get(name).get('password')exceptAttributeError:print("\033[1;31;40mUsername '%s' doesn't existed\033[0m" %name)return

if md5_digest(pwd) ==password:

login_time=time.time()

last_login_time= db.get(name).get('last_login_time')if login_time - last_login_time \033[0m"

%datetime.datetime.fromtimestamp(last_login_time).isoformat())

db[name]['last_login_time'] =login_timeprint("\033[1;32;40mwelcome back\033[0m", name)else:print("\033[1;31;40mlogin incorrect\033[0m")defmd5_digest(plain_pass):returnhashlib.md5(plain_pass).hexdigest()defshowmenu():#print '>>>', db

globaldb

prompt= """(N)ew User Login

(E)xisting User Login

(Q)uit

Enter choice:"""done=Falsewhile notdone:

chosen=Falsewhile notchosen:try:

choice=input(prompt).strip()[0].lower()except(EOFError, KeyboardInterrupt):

choice= "q"

print ("\nYou picked: [%s]" %choice)if choice not in "neq":print ("invalid option, try again")else:

chosen=Trueif choice == "q": done =Trueif choice == "n": newuser()if choice == "e": olduser()

db.close()if __name__ == "__main__":

showmenu()

View Code

python shelve模块_python之shelve模块相关推荐

  1. python shelve模块_Python中shelve模块

    Python中Shelve模块是对象持久化保存方法,将对象保存到文件里面,缺省(即默认)的数据存储文件是二进制的,可以作为一个简单的数据存储方案.使用时,只需要使用open函数获取一个shelf对象, ...

  2. python必学的模块_Python常用的模块

    模块和包 1.1模块介绍模块定义:一系列功能的集合体 模块使用: import导入模块 或者 from ... import... 导入模块 模块分类:内置模块 自定义模块 第三方模块 模块加载顺序: ...

  3. 简述python中怎样导入模块_Python中导入模块的两种模式,import

    import import pandas import pandas as pd 使用函数方式:.(),或者.() 比如 pandas.read_csv("data/stock.csv&qu ...

  4. python的窗口处理模块_python的图像处理模块

    除了opencv专门用来进行图像处理,可以进行像素级.特征级.语义级.应用级的图像处理外,python中还有其他库用来进行简单的图像处理,比如图像的读入和保存.滤波.直方图均衡等简单的操作,下面对这些 ...

  5. python安装os模块_python的os模块(ipython,文件,目录,权限,管理)

    什么是os模块 os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,根据不同的平台进行相应的操作,在python编程时,经常和文件.目录打交道,这时就离不了o ...

  6. python psycopg2使用_Python中用psycopg2模块操作PostgreSQL方法

    其实在Python中可以用来连接PostgreSQL的模块很多,这里比较推荐psycopg2.psycopg2安装起来非常的简单(pip install psycopg2),这里主要重点介绍下如何使用 ...

  7. python中自带的模块_python中的模块详解

    概念 python中的模块是什么?简而言之,在python中,一个文件(以".py"为后缀名的文件)就叫做一个模块,每一个模块在python里都被看做是一个独立的文件.模块可以被项 ...

  8. python xlrd模块_python之xlrd模块

    xlrd模块 一.xlrd模块 1.python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库,这两个适用于.xls格式有效 2. xlrd模块 ...

  9. c调用python第三方库_Python使用ctypes模块调用DLL函数之C语言数组与numpy数组传递...

    在Python语言中,可以使用ctypes模块调用其它如C++语言编写的动态链接库DLL文件中的函数,在提高软件运行效率的同时,也可以充分利用目前市面上各种第三方的DLL库函数,以扩充Python软件 ...

最新文章

  1. 服务器可视化_系统管理员不可错过的6款服务器监控工具
  2. rsync配置与应用(转)
  3. 网元查看一个无厘头的core dump问题定位
  4. 如何提高Linux下块设备IO的整体性能?
  5. OpenJDK 正式宣布AWT、2D、Swing等项目解散
  6. 鸿蒙系统天气,墨迹天气携手鸿蒙系统 以精细化气象服务助力全场景生态建设...
  7. .net core HttpContext(Http上下文)
  8. 阿里云李飞飞:什么是云原生数据库
  9. mysql启动startpost_(转)percona的安装、启动、停止
  10. Oracle shared_pool_reserved_size参数设置说明
  11. 【题解】Luogu p3478 [POI2008]STA-Station 动态规划
  12. 最新最全MTK联发科手机芯片型号及参数汇总
  13. pythonpath环境变量pth_.pth 文件扩展python环境路径
  14. 聊聊这个本不存在的 “元宇宙”
  15. ICPC焦作站(E、F)+思维+树上dp
  16. 技术人的充电时刻,200分钟QA交流,尽在SDCC 2017·深圳站
  17. vbo,ibo,vao
  18. 如何高效学习,学习IT知识(转载)
  19. 计算机专业复试简历超实用
  20. python输出26个大写字母怎么读_26个大写字母里的每个字母怎么读?

热门文章

  1. Python爬虫v2-手机价位爬虫
  2. Java 开发环境配置
  3. 在雨课堂上如何打印不凌乱的课件???
  4. 孕期做什么副业好?在家兼职挣钱的孕妇不仅能很好地抚养孩子,还能继续她们的职业生涯
  5. 任达华女儿出道,长腿秒杀成年人
  6. 程序猿身边有个漂亮女程序媛~~~那是种什么样的体验?
  7. 十位互联网一线高工手写Java高级知识,成功入职腾讯
  8. 对象已死,生存还是死亡,这是个问题
  9. Getshell的各种姿势
  10. C语言 自带换行的 printf 函数