1 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
您的代碼中沒有遞歸樹搜索,因此實(shí)際上不需要os.walk()。如果我理解正確,您的代碼將檢查當(dāng)前目錄的確切名稱,然后一直向上搜索FS。
path = os.path.dirname("/path/to/file.mp3")
target = "test.xml"
top = "/"
while True:
if os.path.isfile(os.path.join(path,target)):
#found
break
if path==top: #alternative check for root dir: if os.path.dirname(path)==path
#not found
break
path=os.path.dirname(path)
一種替代方法是使用生成父目錄的生成器,但對(duì)我而言似乎過于復(fù)雜。盡管這可能更像pythonic:
def walk_up(path,top):
while True:
yield path
if path==top: raise StopIteration
else: path=os.path.dirname(path)
found = None
for p in walk_up(os.path.dirname("/path/to/file.mp3"),"/"):
p = os.path.join(p,target)
if os.path.isfile(p):
#found
found = p
break
else:
#not found
添加回答
舉報(bào)