我正在尝试编写一个函数,它将搜索目录树中的“搜索”目录并返回到它的路径,它应该在找到目录时停止,但它不是,我的错误在哪里?
import os
searched = "NodeBook"
def find(Path, searched):
print("Searching in " + os.path.normpath(Path))
for filePath in os.listdir(Path):
if ((filePath == searched) and (os.path.isdir(os.path.join(Path, filePath)))) :
print("Found")
print(filePath)
print(os.path.join(Path, filePath))
return os.path.join(Path, filePath)
elif (os.path.isdir(filePath)) :
find(os.path.join(Path, filePath), searched)
find( "./", searched)我希望是这样的:
Searching in .
Searching in nodeLearning
Searching in nodeParse
Searching in Screeps
Found
NodeBook但我有:
Searching in .
Searching in nodeLearning
Searching in nodeParse
Searching in Screeps
Found
NodeBook
./Screeps\NodeBook
Searching in testpython
Searching in testReact
Searching in testReact\testreact它会遍历所有子目录。
发布于 2019-06-14 19:53:16
你有一些小问题。
Bug 1:您看的是isdir(filePath)而不是isdir(os.path.join(Path, filePath))。如果在起始位置有一个与目录名称不同的目录,则这可能会导致错误。例如
/tmp/a <-- dir
/tmp/b <-- dir
/tmp/b/a <-- file会给OSError
Bug 2:如果在递归调用中找到匹配项,则不会停止--您可以通过多种方法修复这个问题,选择通过检查递归调用中的返回来实现这一点。
Bug 3:我认为,如果遇到形成循环的符号链接,这可能会永远持续下去。没有修好,但你应该决定如何处理它。
为了清晰起见,我还重新命名了几个东西。
import os
def find_subdir(base_dir, search):
print("Searching in " + os.path.normpath(base_dir))
for name in os.listdir(base_dir):
path = os.path.join(base_dir, name)
if not os.path.isdir(path):
continue
if name == search:
return path
sub_search = find_subdir(path, search)
if sub_search is not None:
return sub_search
return None # For clarity
result = find_subdir( "./", "NodeBook")
if result is not None:
print("Found")
print(result)发布于 2019-06-14 19:37:53
在这里,该函数正在调用自己:
elif (os.path.isdir(filePath)) :
find(...)好的,但是这是在循环中发生的,所以在这个调用返回之后,循环将继续。您应该重新考虑逻辑:也许您可以检查返回值,然后返回它,如果它指示有效的路径,或者继续循环,否则。
例如,现在函数在未找到任何内容时返回None,因此可以检查返回值是否为None。
ret = find(...)
if ret is not None:
return ret
# continue looping otherwisehttps://stackoverflow.com/questions/56604184
复制相似问题