简体   繁体   English

将路径拆分为子文件夹的“三角形”

[英]Split path into 'triangle' of subfolders

I want to split a path into its components and handle each directory in order from the bottom. 我想将路径拆分为其组件,并从底部开始按顺序处理每个目录。 For 对于

path = 'a/b/c/d'

I want to get 我想得到

components = [
    ('', 'a'),
    ('a', 'b'),
    ('a/b', 'c'),
    ('a/b/c', 'd')
]

Is there something in the standard library to help me with the task? 标准库中有什么可以帮助我完成任务的吗?

This works, although I would prefer something better looking and hopefully less error prone. 尽管我希望外观更好,但希望不会出现错误,但这种方法行得通。

>>> comp = os.path.normpath('a/b/c/d').split(os.sep)
>>> [(os.path.join(*comp[:i]) if comp[:i] else '', comp[i]) for i in range(len(comp))]
[('', 'a'), ('a', 'b'), ('a/b', 'c'), ('a/b/c', 'd')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM