import os
import sys
sys.setrecursionlimit(1000000)
def searchFilePath(filename, path):
try:
for direction in os.listdir(path):
if direction == filename:
print(path)
break
elif os.path.isfile(os.path.join(path, direction)):
continue
else:
searchFilePath(filename, os.path.join(path, direction))
except PermissionError:
pass
searchFilePath("abc.rar", "d:\\")
每次程序找到目标文件时,虽然我使用break来结束递归,但它无法立即停止。它总是经过路径下的所有路径,然后返回结果。
答案 0 :(得分:2)
break
仅结束当前循环。不退出调用堆栈中正在进行的任何循环。
你必须从函数返回一个标志,这样父调用才能知道退出:
def searchFilePath(filename, path):
try:
for direction in os.listdir(path):
if direction == filename:
print(path)
return True
elif os.path.isfile(os.path.join(path, direction)):
continue
else:
found = searchFilePath(filename, os.path.join(path, direction))
if found:
return True
except PermissionError:
pass
return False
答案 1 :(得分:1)
break
只留下当前循环。您必须使用返回值来表示递归的结束
def searchFilePath(filename, path):
""" returns True if the filename was found in path """
try:
for direction in os.listdir(path):
if direction == filename:
print(path)
return True
elif not os.path.isfile(os.path.join(path, direction)):
if searchFilePath(filename, os.path.join(path, direction)):
return True
except PermissionError:
pass
return False
或者如果您想进一步使用path
:
def searchFilePath(filename, path):
""" returns the path, where the filename was found """
try:
for direction in os.listdir(path):
if direction == filename:
return path
elif not os.path.isfile(os.path.join(path, direction)):
found = searchFilePath(filename, os.path.join(path, direction)):
if found is not None:
return found
except PermissionError:
pass
return None
如果您使用os.walk
,则可以将功能简化为:
def searchFilePath(filename, path):
for path, _, filenames in os.walk(path):
if filename in filenames:
return path
return None
答案 2 :(得分:1)
您使用break
错误。 break
会让你脱离一个循环。
for x in some_list:
for y in another_list:
for z in yet_another_list:
break
这将继续遍历another_list
中的所有值。
你想使用return
,这将使你脱离整个功能。
for x in some_list:
for y in another_list:
for z in yet_another_list:
return z
请注意,这会在yet_another_list
的第一次迭代中停止,并且仅作为代码无法正常工作的示例。