用短语搜索hardrive上的项目。

2024-09-25 00:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试设置一个程序,在其中有输入的内容,将在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

Tags: 代码inimport程序内容pngoswindows
1条回答
网友
1楼 · 发布于 2024-09-25 00:35:54

问题是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

相关问题 更多 >