Python Data Persistence 简明教程
Python Data Persistence - Shelve Module
Python 标准库中的 shelve 模块提供了简单但有效的对象持久性机制。此模块中定义的 shelf 对象是类似于字典的对象,它持久性地存储在磁盘文件中。这会创建一个类似于 UNIX 类系统上的 dbm 数据库的文件。
The shelve module in Python’s standard library provides simple yet effective object persistence mechanism. The shelf object defined in this module is dictionary-like object which is persistently stored in a disk file. This creates a file similar to dbm database on UNIX like systems.
shelf 字典有一些限制。仅字符串数据类型可以作为此特殊字典对象中的键,而任何可 pickle 的 Python 对象都可以作为值。
The shelf dictionary has certain restrictions. Only string data type can be used as key in this special dictionary object, whereas any picklable Python object can be used as value.
shelf 模块定义了以下三种类:
The shelve module defines three classes as follows −
Sr.No |
Shelve Module & Description |
1 |
Shelf This is the base class for shelf implementations. It is initialized with dict-like object. |
2 |
BsdDbShelf This is a subclass of Shelf class. The dict object passed to its constructor must support first(), next(), previous(), last() and set_location() methods. |
3 |
DbfilenameShelf This is also a subclass of Shelf but accepts a filename as parameter to its constructor rather than dict object. |
shelve 模块中定义的 open() 函数返回 DbfilenameShelf 对象。
The open() function defined in shelve module which return a DbfilenameShelf object.
open(filename, flag='c', protocol=None, writeback=False)
filename 参数被分配到创建的数据库。flag 参数的默认值为 "c",用于读/写访问。其他标记为 "w"(仅写)、"r"(仅读)和 "n"(新建,读/写)。
The filename parameter is assigned to the database created. Default value for flag parameter is ‘c’ for read/write access. Other flags are ‘w’ (write only) ‘r’ (read only) and ‘n’ (new with read/write).
序列化本身受 pickle 协议控制,默认为 none。最后一个参数 writeback 参数默认为 false。如果设置为 true,会缓存访问的条目。每次访问都会调用 sync() 和 close() 操作,因此进程可能会很慢。
The serialization itself is governed by pickle protocol, default is none. Last parameter writeback parameter by default is false. If set to true, the accessed entries are cached. Every access calls sync() and close() operations, hence process may be slow.
以下代码创建一个数据库并在其中存储字典条目。
Following code creates a database and stores dictionary entries in it.
import shelve
s=shelve.open("test")
s['name']="Ajay"
s['age']=23
s['marks']=75
s.close()
这会在当前目录中创建 test.dir 文件并将键值数据存储在哈希形式中。Shelf 对象提供以下方法:
This will create test.dir file in current directory and store key-value data in hashed form. The Shelf object has following methods available −
Sr.No. |
Methods & Description |
1 |
close() synchronise and close persistent dict object. |
2 |
sync() Write back all entries in the cache if shelf was opened with writeback set to True. |
3 |
get() returns value associated with key |
4 |
items() list of tuples – each tuple is key value pair |
5 |
keys() list of shelf keys |
6 |
pop() remove specified key and return the corresponding value. |
7 |
update() Update shelf from another dict/iterable |
8 |
values() list of shelf values |
若要访问内容中特定键的值 −
To access value of a particular key in shelf −
s=shelve.open('test')
print (s['age']) #this will print 23
s['age']=25
print (s.get('age')) #this will print 25
s.pop('marks') #this will remove corresponding k-v pair
内置词典对象中,items()、keys() 和 values() 方法返回视图对象。
As in a built-in dictionary object, the items(), keys() and values() methods return view objects.
print (list(s.items()))
[('name', 'Ajay'), ('age', 25), ('marks', 75)]
print (list(s.keys()))
['name', 'age', 'marks']
print (list(s.values()))
['Ajay', 25, 75]
若要将其他字典与内容的项目合并,请使用 update() 方法。
To merge items of another dictionary with shelf use update() method.
d={'salary':10000, 'designation':'manager'}
s.update(d)
print (list(s.items()))
[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]