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])
添加回答
舉報