Skip to main content

PyFolder 是一个用于将文件系统文件夹作为字典进行管理的包。

项目描述

PyFolder是一个用于将文件系统文件夹作为字典进行管理的包。

https://badge.fury.io/py/pyfolder.svg https://travis-ci.org/ipazc/pyfolder.svg?branch=master https://coveralls.io/repos/github/ipazc/pyfolder/badge.svg?branch=master 代码健康

安装

目前仅支持Python 3.4.1 及更高版本:

sudo pip3 install pyfolder

例子

>>> from pyfolder import PyFolder
>>>
>>> pyfolder = PyFolder("/path/to/folder")
>>> pyfolder["file.txt"] = "hello, this is going to be instantly the content of this file."

基本用法

PyFolder可以轻松地从文件系统存储或读取内容。用法与普通字典相同:

  • 创建具有特定二进制内容的文件:

>>> from pyfolder import PyFolder
>>>
>>> pyfolder = PyFolder("/path/to/folder")
>>> pyfolder['file.bin'] = b"Content as bytes"
>>> pyfolder['file.txt'] = "Content as text"
>>> pyfolder['file.json'] = {"content": "Content as JSON"}

PyFolder自动检测要存储的内容类型。

也可以使用相对文件 URI 表示法来引用文件的创建:

>>> pyfolder["folder1/folder2/file.txt"] = "content"

如果指定的文件夹不存在,默认情况下它将自动创建,除非在实例化过程中将标志auto_create_folder设置为False :

>>> pyfolder = PyFolder("/path/to/folder", auto_create_folder=False)

注意 ”。” URI 表示法中不允许使用“..”字符,它必须是根的相对 URI。

  • 获取具体内容:

>>> pyfolder = PyFolder("/path/to/folder")
>>> pyfolder['file.bin']
b"Content as bytes"
>>> pyfolder['file.txt']
"Content as text"
>>> pyfolder['file.json']
{"content": "Content as JSON"}
>>> pyfolder['folder1/folder2/file.bin']
b"Other content"

默认情况下, PyFolder将根据文件扩展名尝试使用它拥有的最佳解释器加载内容。如果没有找到内容的解释器,它将以字节格式返回内容。可以在实例化期间使用标志解释 = False禁用此行为:

>>> pyfolder = PyFolder("/path/to/folder", interpret=False)
  • 编辑内容:

PyFolder不允许修改或删除元素,除非在实例化期间指定了标志allow_override

>>> pyfolder = PyFolder("/path/to/folder", allow_override=True)
>>> pyfolder['file.bin'] = b"replaced_content_bytes"
  • 删除内容:

>>> del pyfolder['file.bin']

请注意,也可以删除文件夹:

>>> del pyfolder['folder1']
>>> del pyfolder['.']  # deletes PyFolder root folder

默认情况下,除非文件夹内容为空,否则 PyFolder 不会删除文件夹。为了能够不受限制地删除文件夹,请启用标志allow_remove_folders_with_content

>>> pyfolder = PyFolder("/path/to/folder", allow_remove_folders_with_content=True)
  • 遍历文件:

默认情况下, PyFolder允许迭代文件,包括文件夹:

>>> for file_name in pyfolder:
>>>    print(file_name)

如果还想访问内容,可以使用items()方法完成:

>>> for file_name, content in pyfolder.items():
>>>    print(file_name, content)

如果只需要文件,则存在files()方法来达到目的:

>>> for file_name in pyfolder.files()
...
>>> for file_name, content in pyfolder.files_items()
  • 遍历文件夹:

>>> for folder_name in pyfolder.folders():
...

也可以同时遍历文件夹名称及其内容:

>>> for folder_name, folder_content in pyfolder.folders_items():
...

PyFolder中,每个文件夹都是一个PyFolder对象。完全可以按如下方式嵌套文件夹:

>>> pyfolder["folder1"]["folder2"]
>>> pyfolder["folder1/folder2"]  # Equivalent in relative URI notation
  • 搜索文件:

PyFolder通过匹配名称来简化文件/文件夹的搜索。它将返回找到的文件名的相对 URI 列表:

>>> pyfolder.index("name.bin")
>>> ['path/to/name.bin', 'path2/to/name.bin']

执照

它是在 MIT 许可下发布的。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

pyfolder-0.0.2.tar.gz (9.5 kB 查看哈希)

已上传 source