3 回答

TA贡献1818条经验 获得超7个赞
使用pathlib. PurePaths 为与文件系统没有关系的类路径对象提供抽象接口。特别PurePosixPath是使用正斜杠 ( /) 作为分隔符的类型:
>>> from pathlib import PurePosixPath
>>> p = PurePosixPath('/house/dogs/ralph/bone')
>>> str(p.parent)
/house/dogs/ralph
>>> str(p.parent.parent)
/house/dogs
您可以轻松循环:
p = PurePosixPath(...)
while p != p.root:
# Do stuff to p
p = p.parent
一个相当 Pythonic 的画龙点睛是使它成为一个生成器:
def receding_path(p):
p = PurePosixPath(p)
while p != p.root:
yield str(p)
p = p.parent
for item in receding_path('/house/dogs/ralph/bone'):
# do stuff to each item

TA贡献1801条经验 获得超8个赞
一种方法是拆分字符串"/"并连续切片。
in_string = "/house/dogs/ralph/bone"
s = in_string.split("/")
out_strings = list(filter(None, ("/".join(s[:i+1]) for i in range(len(s)))))
print(out_strings)
#['/house', '/house/dogs', '/house/dogs/ralph', '/house/dogs/ralph/bone']
该filter(None, ...)用于去除空字符串。
如果您希望按照您在帖子中指定的顺序输出,或者反转范围:
out_strings = list(filter(None, ("/".join(s[:i]) for i in range(len(s), 0, -1))))
print(out_strings)
#['/house/dogs/ralph/bone',
# '/house/dogs/ralph',
# '/house/dogs',
# '/house']

TA贡献1862条经验 获得超7个赞
前两个答案的组合:
import pathlib
import os
def resources(path):
parts = pathlib.Path(path).parts
for n in range(len(parts), 1, -1):
yield os.path.join(*parts[:n])
添加回答
举报