首先,您需要search
返回成功或失败:
def search(directory):
for files in os.listdir(directory):
fileItem = os.path.join(directory, files)
fileItemStatInfo = os.stat(fileItem)
if S_ISDIR(fileItemStatInfo.st_mode):
return search(fileItem)
elif S_ISREG(fileItemStatInfo.st_mode):
print("Searching", fileItem)
if lookfor in files:
print("\nThe File Has Been Found: %s" % join(directory, lookfor))
return True
(请注意,如果我们从for
循环的末尾掉下来,我们就会从函数的末尾掉下来,这意味着我们 return None
。因此,函数 an only return True
,with 是真的,或者None
,不是。)
现在,您只需循环直到它返回真值:
while True:
lookfor=input("\nPlease enter file name you want to search? \n")
if search(lookfor):
break
print('Could not find that file, sorry. Try again.')
综上所述,我认为search
它并没有达到你想要的效果——而且你也可以极大地简化它。
首先,我不确定您是尝试将其lookfor
用作全局变量,还是用作search
函数内的闭包……但无论哪种方式,您可能都不应该这样做。将其作为参数传递。
此外,拥有一个名为的变量files
来保存每个文件名,而不是它们的集合,这非常令人困惑。
如果您想递归地遍历目录树,请使用os.walk
而不是尝试自己实现它。
您可能应该打印出找到的文件名,而不是寻找的片段。
把它放在一起:
def search(lookfor, directory):
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
if lookfor in filename:
print("\nThe File Has Been Found: %s" % join(dirpath, filename))
return True
当然,在大多数实际代码中,您可能希望返回路径名,因此您的其余代码可以使用它(例如,打开文件),而不仅仅是打印出来:
def search(lookfor, directory):
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
if lookfor in filename:
return join(dirpath, filename)
while True:
lookfor=input("\nPlease enter file name you want to search? \n")
path = search(lookfor)
if path:
break
print('Could not find that file, sorry. Try again.')
with open(path) as f:
pass # now we can actually use the file we searched so hard for