简体   繁体   English

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

[英]How to suppress unnecessary output produced by fnmatch in Python?

I want to check is a file with a specific name exists or not in a directory.我想检查目录中是否存在具有特定名称的文件。 The directory contains 3 files:该目录包含 3 个文件:

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

The code that I'm using:我正在使用的代码:

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')

If I run the above code like this:如果我像这样运行上面的代码:

python check_files.py 20210401 python check_files.py 20210401

I get this output:我得到这个 output:

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

The desired output would be only the first line:所需的 output 将只是第一行:

20210401.NYSE.csv EXISTS

How do I suppress the rest of the output (ie the filenames that do not match the pattern?)如何抑制 output 的 rest (即与模式不匹配的文件名?)

Following my comment, to get your complete desired output, I think you should use a function, for example:根据我的评论,要获得您想要的完整 output,我认为您应该使用 function,例如:

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())

NB: fnmatch.fnmatch(name, pattern) tests if first parameter 'filename' matches second parameter 'pattern'注意: fnmatch.fnmatch(name, pattern) 测试第一个参数 'filename' 是否匹配第二个参数 'pattern'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM