anydbm is a generic interface to variants of the DBM database — dbhash (requires bsddb), gdbm, or dbm. 如果没有安装这些模块,则将使用模块dumbdbm中的缓慢但简单的实现。
打开数据库文件filename并返回相应的对象。
如果数据库文件已经存在,则使用whichdb模块来确定其类型,并使用相应的模块;如果不存在,则使用可以导入的上面列出的第一个模块。
可选的标志参数必须是以下值之一:
Value | Meaning |
---|---|
'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进行修改)。
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:
Close the anydbm database.
See also