如果没有找到符合搜索条件的文件,则使用 os.walk 搜索文件 - Python

Searching for files with os.walk if no files are found matching the search criteria- Python

现在我正在使用 os.walk 递归搜索任何 autorun.inf 文件的目录和子目录。我知道我没有以最好的方式做到这一点,所以如果您也有更好的方法,请告诉我。如果它找到任何与自动运行匹配的内容,它将为找到的每个符合条件的文件输出文件内容。 但是,当我尝试为如果没有找到匹配的文件做一个 else 语句时,它会为每个不匹配的文件打印 "No file matching the criteria found" 而不是只打印一次(如果有意义的话)。如果找不到符合条件的文件,我只希望它说一次。 这是我目前所拥有的。

import os
from os.path import join
for (dirname, dirs, files) in os.walk('/home/user/Documents/mystuff'):
    for filename in files:
    if filename.startswith('autorun'):
        thefile = os.path.join(dirname,filename)
        f = open(thefile)
        print f.read()
    else:
        print "No file matched the criteria"
found = False

for (dirname, dirs, files) in os.walk('/home/user/Documents/mystuff'):
    for filename in files:
        if filename.startswith('autorun'):
            thefile = os.path.join(dirname,filename)
            f = open(thefile)
            print f.read()
            found = True

if not found:
    print "No file matched the criteria"