Python的anydbm模版和shelve模版 Python中的anydbm模版和shelve模版使用指南

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python的anydbm模版和shelve模版 Python中的anydbm模版和shelve模版使用指南

  2021-03-21 我要评论
想了解Python中的anydbm模版和shelve模版使用指南的相关内容吗,在本文为您仔细讲解Python的anydbm模版和shelve模版的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,anydbm,shelve,下面大家一起来学习吧。

好久没写这系列的文章了,我越来越喜欢用python了,它在我的工作中占据的比例越来越大。废话少说,直接进入主题。

 anydbm允许我们将一个磁盘上的文件与一个“dict-like”对象关联起来,操作这个“dict-like”对象,就像操作dict对象一样,最后可以将“dict-like”的数据持久化到文件。对这个”dict-like”对象进行操作的时候,key和value的类型必须是字符串。下面是使用anydbm的例子:
   

#coding=utf-8
 
import anydbm
 
def CreateData():
  try:
    db = anydbm.open('db.dat', 'c')
    
# key与value必须是字符串
    
# db['int'] = 1
    
# db['float'] = 2.3
    db['string'] = "I like python."
    db['key'] = 'value'
  finally:
    db.close()
 
def LoadData():
  db = anydbm.open('db.dat', 'r')
  for item in db.items():
    print item
  db.close()
 
if __name__ == '__main__':
  CreateData()
  LoadData()

anydbm.open(filename[, flag[, mode]]),filename是关联的文件路径,可选参数flag可以是: ‘r': 只读, ‘w': 可读写, ‘c': 如果数据文件不存在,就创建,允许读写; ‘n': 每次调用open()都重新创建一个空的文件。mode是unix下文件模式,如0666表示允许所有用户读写。
    shelve模块是anydbm的增强版,它支持在”dict-like”对象中存储任何可以被pickle序列化的对象,但key也必须是字符串。同样的例子,与shelve来实现:
 

import shelve
 
def CreateData():
  try:
    db = shelve.open('db.dat', 'c')
    
# key与value必须是字符串
    db['int'] = 1
    db['float'] = 2.3
    db['string'] = "I like python."
    db['key'] = 'value'
  finally:
    db.close()
 
def LoadData():
  db = shelve.open('db.dat', 'r')
  for item in db.items():
    print item
  db.close()
 
if __name__ == '__main__':
  CreateData()
  LoadData()

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们