路径操作库
项目描述
betterpath,或“bp”,是对经典Twisted FilePath 类型及其接口的改编。bp提供了一种简单、健壮、经过良好测试的对象抽象,覆盖了文件路径,并将文件路径的概念推广到了文件系统之外。
文件路径
bp公开了一个文件路径的接口,bp.abstract.IFilePath,并提供以下具体实现
bp.filepath.FilePath,用于根文件系统
bp.zippath.ZipPath,用于ZIP存档
bp.memory.MemoryPath,用于内存中的临时文件系统
此外,还有可以围绕其他文件路径包装的组合抽象文件路径
bp.readonly.ReadOnlyPath,用于只读文件系统
API文档可在http://betterpath.rtfd.org/找到。
与竞争对手相比
os.path
备受尊敬的冠军,os.path多年来一直是Python路径问题的原因和解决方案。
优点
在标准库中
缺点
不安全
冗长
在strs上操作
没有用于功能性的接口或ABC
仅覆盖根文件系统
pathlib
pathlib希望通过PEP 428开辟一条通往伟大的道路。
优点
方便的__div__()重载
缺点
没有用于功能性的接口或ABC
仅覆盖根文件系统
示例
将数据保存到磁盘
旧方法
def save(base, fragments, data): # `fragments` could contain unsafe paths! if ".." in fragments or "." in fragments: raise ValueError("Unsafe paths!") path = os.path.join(os.path.abspath(base), os.sep.join(fragments)) # Alternatively: path = os.path.join(os.path.abspath(base), *fragments) # I hope that this doesn't fail mid-write! Also, did the directories # exist? I think so, yes. with open(path, "wb") as handle: handle.write(data)
新方法
def save(base, fragments, data): path = base.descendant(fragments) path.parent().makeDirs() path.setContent(data)
变更日志
0.2
首次发布