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

如何在Python中抑制fnmatch产生的不必要输出?,python,fnmatch,Python,Fnmatch,我想检查目录中是否存在具有特定名称的文件。该目录包含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.lis

我想检查目录中是否存在具有特定名称的文件。该目录包含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())

注意:fnmatch.fnmatch(名称,模式)测试第一个参数'filename'是否与第二个参数'pattern'匹配。

抑制else语句,您将获得所需的输出