[英]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
我得到這個 output:
20210401.NYSE.csv EXISTS
20210402.NYSE.csv DOES NOT EXIST
20210403.NYSE.csv DOES NOT EXIST
所需的 output 將只是第一行:
20210401.NYSE.csv EXISTS
如何抑制 output 的 rest (即與模式不匹配的文件名?)
根據我的評論,要獲得您想要的完整 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())
注意: fnmatch.fnmatch(name, pattern) 測試第一個參數 'filename' 是否匹配第二個參數 'pattern'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.