11.6。 anydbm - 对DBM样式数据库的通用访问

Note

在Python 3中,anydbm模块已重命名为dbm当您将源转换为Python 3时,2to3工具将自动调整导入。

anydbm is a generic interface to variants of the DBM database — dbhash (requires bsddb), gdbm, or dbm. 如果没有安装这些模块,则将使用模块dumbdbm中的缓慢但简单的实现。

anydbm.open(filename[, flag[, mode]])

打开数据库文件filename并返回相应的对象。

如果数据库文件已经存在,则使用whichdb模块来确定其类型,并使用相应的模块;如果不存在,则使用可以导入的上面列出的第一个模块。

可选的标志参数必须是以下值之一:

ValueMeaning
'r'Open existing database for reading only (default)
'w'Open existing database for reading and writing
'c'Open database for reading and writing, creating it if it doesn’t exist
'n'Always create a new, empty database, open for reading and writing

如果未指定,默认值为'r'

可选的模式参数是文件的Unix模式,仅在必须创建数据库时使用。它默认为八进制0666(并将由当前的umask进行修改)。

exception anydbm.error

A tuple containing the exceptions that can be raised by each of the supported modules, with a unique exception also named anydbm.error as the first item — the latter is used when anydbm.error is raised.

open()返回的对象支持大部分与字典相同的功能;键和它们对应的值可以被存储,检索和删除,并且has_key()keys()方法可用。Keys and values must always be strings.

以下示例记录一些主机名和相应的标题,然后打印出数据库的内容:

import anydbm

# Open database, creating it if necessary.
db = anydbm.open('cache', 'c')

# Record some values
db['www.python.org'] = 'Python Website'
db['www.cnn.com'] = 'Cable News Network'

# Loop through contents.  Other dictionary methods
# such as .keys(), .values() also work.
for k, v in db.iteritems():
    print k, '\t', v

# Storing a non-string key or value will raise an exception (most
# likely a TypeError).
db['www.yahoo.com'] = 4

# Close when done.
db.close()

In addition to the dictionary-like methods, anydbm objects provide the following method:

anydbm.close()

Close the anydbm database.

See also

Module dbhash
BSD db database interface.
Module dbm
Standard Unix database interface.
Module dumbdbm
Portable implementation of the dbm interface.
Module gdbm
GNU database interface, based on the dbm interface.
Module shelve
General object persistence built on top of the Python dbm interface.
Module whichdb
Utility module used to determine the type of an existing database.

Previous topic

11.5. marshal — Internal Python object serialization

Next topic

11.7. whichdb — Guess which DBM module created a database

This Page