使用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.parentfor item in receding_path('/house/dogs/ralph/bone'): # do stuff to each item
一种方法是拆分字符串"/"并连续切片。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']
前两个答案的组合:import pathlibimport osdef resources(path): parts = pathlib.Path(path).parts for n in range(len(parts), 1, -1): yield os.path.join(*parts[:n])