python中的文件搜索
我想要一个函数,它接受一个字符串参数(数据),并将该字符串拆分为单词(word)。然后,它应该获取目录中的所有文件,获取每个文件名,并检查文件名中是否存在所有单词。 如果存在,则打印文件名并打印“是否要打开”如果是,则打印“已打开”并中断所有循环。如果否,则应继续搜索 最后,它应该打印文件是否存在于目录中 这是我写的代码python中的文件搜索,python,python-2.7,Python,Python 2.7,我想要一个函数,它接受一个字符串参数(数据),并将该字符串拆分为单词(word)。然后,它应该获取目录中的所有文件,获取每个文件名,并检查文件名中是否存在所有单词。 如果存在,则打印文件名并打印“是否要打开”如果是,则打印“已打开”并中断所有循环。如果否,则应继续搜索 最后,它应该打印文件是否存在于目录中 这是我写的代码 def file_search(data): data = data.split() for root, dirs, files in os.walk("/media
def file_search(data):
data = data.split()
for root, dirs, files in os.walk("/media/", topdown=False):
word_match = True
opened = False
if not opened:
for name in files:
for word in data:
if word not in name:
word_match = False
if word_match:
print "file found:" + name + "where path is" + root
print "do you want to open it "
answer = raw_input()
if answer == "yes" :
opened = True
print "file opened"
break
不知怎的,我把它修好了
def file_search2(name, name_words):
check = True
for word in name_words:
if word not in name:
check = False
break
return check
def file_search(filename):
file_found = False
file_opened = False
words = filename.split()
for root, dirs, files in os.walk('/media/', topdown=False):
for name in files:
if file_search2(name, words) and file_opened == False:
file_found = True
print "file found :" + name
print "Do you want to open the file:"
answer = raw_input()
if "yes" in answer:
file_opened = True
print "file opened successfully"
if file_opened == False:
print "file not found"
file_search("file name with space")
你面临的问题是什么?堆栈回溯或特定错误Yutraksh不存在错误。它已成功运行,但未打印任何内容。即使给定的文件存在于目录中,也可能是因为您没有在脚本中调用函数,您刚刚声明了它,请使用
file\u search(“文件名”)
调用您的函数。我是从另一个文件调用它的