Search code examples
pythonglob

Using partial wildcard in Glob


I haven't been able to find a use case of this, but basically I was trying to utilize glob for a part of the filename.

file_name_date = time.strftime("%m%d%y")
h_server = time.strftime("%-I%p")    
filename = 'PRD.FRB.D01.INTRADAY.GGV1051.' + file_name_date + '.' + h_server + '.txt'

This works fine in my code, however now the GGV1051 is changing with each file, so I was hoping to do something like

filename = glob('PRD.FRB.D01.INTRADAY.' + * + '.' + file_name_date + '.' + h_server + '.txt'

But I'm not sure how to proceed. I didn't see a clear path with either fnmatch or glob, but I'm not well versed in those libraries.

My thought is to create a string like this:

filename = str('PRD.FRB.D01.INTRADAY.?.' + file_name_date + '.' + h_server + '.txt')

which would yield:

PRD.FRB.D01.INTRADAY.?.062917.12P.txt

and then do something like

glob(filename):

But that doesn't work as intended.

Any thoughts? Thanks!


Solution

  • Use glob to match pathnames like /home/juser/something/*.txt for all text files within /home/juser directory. You can use it to match simple filenames like *.txt for all text files in the current working directory.

    fnmatch.fnmatch and fnmatch.filter are used for filenmaes. The former, tests if a filename matches a pattern and returns True for matched names, otherwise False for unmatched names. The latter, returns the matched filenames according to the giving glob pattern.

    All your filenames begin with PRD.FRB.D01.INTRADAY. and end with .txt suffix, then to match all files that begin with PRD.FRB.D01.INTRADAY. and end with .txt irrespective of what's in the middle:

    glob.glob("PRD.FRB.D01.INTRADAY.*.txt") 
    

    This glob matches any filename that starts with PRD.FRB.D01.INTRADAY. and ends with .txt suffix, it doesn't matter what comes after PRD.FRB.D01.INTRADAY. the * wildcard character matches any arbitrary character. ? matches only one arbitrary character. Note, This matches filenames in the working directory of your script. If you need to match names in a different directory, pass "/path/to/my/PRD.FRB.D01.INTRADAY.*.txt" to glob.