【问题标题】:Searching for files with os.walk if no files are found matching the search criteria- Python如果没有找到与搜索条件匹配的文件,则使用 os.walk 搜索文件 - Python
【发布时间】:2015-08-20 17:11:10
【问题描述】:

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

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"

【问题讨论】:

    标签: python regex os.walk


    【解决方案1】:
    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"
    

    【讨论】:

    • 完美运行!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-09-23
    • 2017-01-10
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多