6.3.3 使用 shelve 模块操作二进制文件

  Python标准库shelve也提供了二进制文件操作的功能,可以像字典赋值一样来写入二进制文件,也可以像字典一样读取二进制文件,有点类似于NoSQL数据库MongoDB。

import shelve

fp = shelve.open('shelve_test.dat')  #创建或打开二进制文件
zhangsan = {'age':38,'sex':'Male','address':'SDIBT'}
fp['zhangsan'] = zhangsan   #往文件里写入内容

lisi = {'age':40,'sex':'Male','qq':'1234567','tel':'7654321'}
fp['lisi'] = lisi

fp.close()

f = shelve.open('shelve_test.dat')
print(fp['zhangsan']['age'])
print(fp['lisi']['qq'])

fp.close()

===========执行报错如下
Traceback (most recent call last):
  File "C:\Users\dddd\AppData\Local\Programs\Python\Python35\lib\shelve.py", line 111, in __getitem__
    value = self.cache[key]
KeyError: 'zhangsan'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/dddd/AppData/Local/Programs/Python/Python35/test1.py", line 13, in <module>
    print(fp['zhangsan']['age'])
  File "C:\Users\dddd\AppData\Local\Programs\Python\Python35\lib\shelve.py", line 113, in __getitem__
    f = BytesIO(self.dict[key.encode(self.keyencoding)])
  File "C:\Users\dddd\AppData\Local\Programs\Python\Python35\lib\shelve.py", line 70, in closed
    raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf


#在Pycharm 上就报这个错,暂时不知道如何解决

 

 1 >>> import shelve
 2 >>> fp=shelve.open('shelve.dat')
 3 >>> zhangsan = {'age':38,'sex':'Male'}
 4 >>> fp['zhangsan'] = zhangsan
 5 >>> fp.close
 6 
 7 >>> f = shelve.open('shelve_test.dat')
 8 >>> fp['zhangsan']['age']
 9 38
10 >>> 

 

转载于:https://www.cnblogs.com/avention/p/8779758.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值