I want to check is a file with a specific name exists or not in a directory. The directory contains 3 files:
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
I get this 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:
20210401.NYSE.csv EXISTS
How do I suppress the rest of the output (i.e. the filenames that do not match the pattern?)
Following my comment, to get your complete desired output, I think you should use a function, for example:
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) tests if first parameter 'filename' matches second parameter 'pattern'