【问题标题】:How to suppress unnecessary output produced by fnmatch in Python?如何抑制 Python 中 fnmatch 产生的不必要输出?
【发布时间】:2021-07-15 03:31:38
【问题描述】:

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

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

【问题讨论】:

  • 抑制 else 语句,你会得到你想要的输出

标签: python fnmatch


【解决方案1】:

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

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(name, pattern) 测试第一个参数 'filename' 是否匹配第二个参数 'pattern'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多