提供对文件的类似maildir的访问
gocept.filestore的Python项目详细描述
文件存储是处理具有多个进程的文件的简单方法 不需要锁。
初始化文件存储
在临时区域中创建文件存储:
>>> import tempfile >>> store_dir = tempfile.mkdtemp() >>> from gocept.filestore import FileStore >>> filestore = FileStore(store_dir) >>> filestore <gocept.filestore.filestore.FileStore object at 0x...>
到目前为止什么都没有发生:
>>> import os >>> os.listdir(store_dir) []
在使用商店之前,我们需要准备:
>>> filestore.prepare()
prepare已创建tmp/new/cur目录结构:
>>> sorted(os.listdir(store_dir)) ['cur', 'new', 'tmp']
再次调用prepare不起任何作用:
>>> filestore.prepare() >>> sorted(os.listdir(store_dir)) ['cur', 'new', 'tmp']
使用文件存储
将文件添加到存储区可以使用create方法:
>>> f = filestore.create('a-file')
在“tmp”区域以“w”模式创建文件(如果未指定):
>>> f <open file '.../tmp/a-file', mode 'w' at 0x...>
我们在tmp区域找到了这个文件。注意filestore.list 它们的完整路径名,这样我们就可以直接将其输入文件/打开:
>>> filestore.list('tmp') ['.../tmp/a-file']
我们有一个普通的文件,请写信给它:
>>> f.write('Die Ente bleibt draussen!') >>> f.close()
我们已经完成了文件的编写,因此可以将它移到 其他应用程序:
>>> filestore.move('a-file', 'tmp', 'new') >>> filestore.list('tmp') [] >>> filestore.list('new') ['.../new/a-file']
move操作使用的os.move应该是原子的。当另一个 进程“看到”它可以直接使用的文件并将其移动到“cur”:
>>> filestore.move('a-file', 'new', 'cur') >>> filestore.list('new') [] >>> filestore.list('cur') ['.../cur/a-file']
文件也可以复制:
>>> filestore.copy('a-file', 'cur', 'tmp') >>> filestore.list('cur') ['.../cur/a-file'] >>> filestore.list('tmp') ['.../tmp/a-file']
清理
测试后删除临时目录:
>>> import shutil >>> shutil.rmtree(store_dir)