使用短语在硬盘上搜索项目。

时间:2017-08-23 20:10:19

标签: python python-3.x

我试图在输入内容的地方设置一个程序,在windows中搜索硬盘(c:\)。我输入了下面输入的代码,但它在lookfor变量中占用了完整路径。我想弄清楚如果我有几个字母匹配停止它们我怎么能设置它。例如,如果我将Curr放在lookfor变量中,我希望它找到Current1.png,但我需要输入全长项(Current1.png)来定位它。

import os
from os.path import join

lookfor = 'Current1.png'
for root, dirs, files in os.walk('c:\\'):
#print ('Searching', root)
if lookfor in files:
    print ('Found: %s' %join(root, lookfor))
    break

1 个答案:

答案 0 :(得分:0)

问题是os.walk()正在返回文件列表,而您正在该文件列表中搜索字符串

files = ['Current1.jpg', 'Current2.jpg', 'Current3.jpg']

如果您在此列表中搜索“Curr”,则无法找到它

>>> 'Curr' in files
False
>>> any(['Curr' in file for file in files])
True

尝试将代码更改为

import os
from os.path import join

lookfor = 'Curr'
for root, dirs, files in os.walk('c:\\'):
    if any([lookfor in file for file in files]):
        print ('Found: %s' %join(root, lookfor))
        break