如何抑制 Python 中 fnmatch 产生的不必要输出?

How to suppress unnecessary output produced by fnmatch in Python?

我想检查目录中是否存在具有特定名称的文件。该目录包含 3 个文件:

20210401.NYSE.csv
20210402.NYSE.csv
20210403.NYSE.csv

我使用的代码:

import sys, os, re, fnmatch

input_dir = '/scripts/test/'
date = sys.argv[1]
midfix = '.NYSE'
data_inpt_patt = date + midfix + '*' 

input_files = os.listdir(input_dir)
    for i in input_files:
        if fnmatch.fnmatch(i, data_inpt_patt):
            print(i + ' EXISTS')
        else:
            print(i + ' DOES NOT EXIST')

如果我运行上面的代码是这样的:

python check_files.py 20210401

我得到这个输出:

20210401.NYSE.csv EXISTS
20210402.NYSE.csv DOES NOT EXIST
20210403.NYSE.csv DOES NOT EXIST

所需的输出只是第一行:

20210401.NYSE.csv EXISTS

如何抑制其余输出(即与模式不匹配的文件名?)

根据我的评论,为了获得您想要的完整输出,我认为您应该使用一个函数,例如:

def check_file_existence():
    for i in input_files:
        if fnmatch.fnmatch(i, data_inpt_patt):
            return data_inpt_patt + ' EXISTS'

    return data_inpt_patt + ' DOES NOT EXIST'



print(check_file_existence())

N.B: fnmatch.fnmatch(name, pattern) 测试第一个参数 'filename' 是否匹配第二个参数 'pattern'