I'm trying to figure out the best way to store a dynamic or changing value in a variable and use the variable as part of my pattern search in fnmatch. Quite possibly fnmatch is not the right way to go?
Trying to keep this as simple as possible. I'm reading in a list of files from a directory which will have a date string that changes from day to day. I want to verify the file I am looking for exists, and for now just print the filename.
This works ...
#!/bin/python
import os
import datetime as dt
import fnmatch
working_dir = '/my/working/dir/'
now = dt.date.today()
f_date = (now.strftime('%Y%m%d'))
print f_date
for root,dirs,files in os.walk(working_dir):
for fname in files:
if fnmatch.fnmatch(fname, '*data*20190923*'):
print fname
exit(0)
What I see is the file I would like to evaluate further on:
20190923
file-data-random_junk.20190923.txt
However What I'd like to do in the pattern line is use f_date
which returns the string 20190923
instead of typing in the date string. Is it possible to match on a combination of text and variable in the pattern string so that I could do something like: if fnmatch.fnmatch(fname, '*data*[my variable]*'):
?
Ok I think I may have answered my own question. Leaving for posterity and in case it helps anyone. All I did was alter the fnmatch line: if fnmatch.fnmatch(fname, '*data*' + f_date + '*'):
which is getting me the result I wanted