1 回答
TA贡献1853条经验 获得超18个赞
您的代码中没有递归树搜索,因此实际上不需要os.walk()。如果我理解正确,您的代码将检查当前目录的确切名称,然后一直向上搜索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)
一种替代方法是使用生成父目录的生成器,但对我而言似乎过于复杂。尽管这可能更像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
添加回答
举报