使用搜索文件os.步行如果没有找到与搜索条件匹配的文件

2024-05-14 14:17:10 发布

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

现在我正在使用os.步行在目录和子目录中递归搜索自动运行.inf文件。我知道我做的不是最好的方法,所以如果你也有更好的方法,请告诉我。如果它找到任何与autorun匹配的内容,它将输出每个符合条件的文件的内容。 但是,当我尝试为if no files been found that matched生成else语句时,它会为每个不匹配的文件打印“no files 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"

Tags: 文件the方法no内容ifosfiles
1条回答
网友
1楼 · 发布于 2024-05-14 14:17:10
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"

相关问题 更多 >

    热门问题