2017-07-25 109 views
-2

我想要一个接受字符串参数(数据)并将该字符串分解为单词(单词)的函数。之后,它应该获取目录中的所有文件,获取每个文件名并检查文件名中是否存在所有单词。 如果存在,则打印文件的名称并打印“是否要打开它”,如果是,则打印“打开”并打破所有循环。如果没有,那么它应该继续搜索。在Python中搜索文件

最后,它应该打印文件是否存在或不在目录中。

这是我写的代码。

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 
+2

您面临的问题是什么?堆栈追溯或错误具体 –

+0

Utraksh没有错误在那里。它运行成功但没有打印任何东西。即使给定的文件存在于目录 – Maan

+0

这可能是因为你没有在你的脚本中调用函数,你刚刚声明了它,使用'file_search(“文件名”)'调用你的函数。 –

回答

0

不知何故我修好了。

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")