zoukankan      html  css  js  c++  java
  • 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:UsersddddAppDataLocalProgramsPythonPython35libshelve.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:UsersddddAppDataLocalProgramsPythonPython35libshelve.py", line 113, in __getitem__
        f = BytesIO(self.dict[key.encode(self.keyencoding)])
      File "C:UsersddddAppDataLocalProgramsPythonPython35libshelve.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 >>> 
  • 相关阅读:
    jquery 锚点跳转、滚动导航菜单和返回顶部
    jQuery attr方法-获得修改元素属性值
    layui中的tab选项卡,循环多个选项卡后不出现折叠的解决方法
    获取地址url的参数值
    vant的tab选项卡的点击事件传参
    css选择器
    jquery实现换一批内容
    letter-spacing 字体间距
    jquery 隔行变色
    Redis与Memcached的区别
  • 原文地址:https://www.cnblogs.com/avention/p/8779758.html
Copyright © 2011-2022 走看看