如何循环这个Python程序
如何循环此代码,以便在未找到其他文件时要求用户搜索该文件如何循环这个Python程序,python,Python,如何循环此代码,以便在未找到其他文件时要求用户搜索该文件 import os, sys from stat import * from os.path import join lookfor = input("\nPlease enter file name you want to search? \n") def search(directory): for files in os.listdir(directory): fileItem = os.pat
import os, sys
from stat import *
from os.path import join
lookfor = input("\nPlease enter file name you want to search? \n")
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):
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))
break
首先,您需要进行
搜索
返回成功或失败:
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
循环的末尾掉下来,我们将从函数的末尾掉下来,这意味着我们返回None
。因此,函数只返回True
,with是truthy,或者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
这个问题太本地化了。我看不出它是通用的。@fgb:事实上,这个通用的问题——“如何循环输入并测试输入?”——非常通用,而且一直都会出现。其他东西(搜索
函数中的所有东西)只是一条红鲱鱼,只是它必须返回一些东西。所以说真的,这很可能是一个dup。但是我找不到一个好的问题来把它联系起来。@abarnert:是的,我想问题的要点是这个问题提出得不好。我们应该找到受骗者,如果它存在的话。