脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python中的anydbm模版和shelve模版使用指南

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

2020-07-21 10:36脚本之家 Python

这篇文章主要介绍了Python中的anydbm模版和shelve模版使用指南,两个模版都可用于数据存储的序列化,需要的朋友可以参考下

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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来实现:
 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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()

延伸 · 阅读

精彩推荐