Kamikaze K
Kamikaze K

Reputation: 191

Use glob to match pattern in string in python

I have a glob pattern that i am trying to use to match and pick some file. I am testing it and it seems to only work on the wild card. The example of files is as below which includes other files not listed but a different extension and that I do not need;

240721_124607_1000_Y1_B.txt.bz2
240721_124607_1000_Z1_B.txt.bz2
240721_124607_1000_X1_B.txt.bz2

The glob pattern that i am using gets all the files with the bz2 extension i.e

files = glob.glob('Z:/{}/{}/DL/*.txt.bz2'.format(directory, folder))

The above works but I want to narrow down to get only the ZI files. I have tried the following patterns but they do not work

files = glob.glob('Z:/{}/{}/DL/?Z1.txt.bz2'.format(directory, folder))

and also tried

files = glob.glob('Z:/{}/{}/DL/Z1*.txt.bz2'.format(directory, folder))

and also tried

files = glob.glob('Z:/{}/{}/DL/?Z1*.txt.bz2'.format(directory, folder))

All the above do not work.

Upvotes: 0

Views: 3540

Answers (1)

Grismar
Grismar

Reputation: 31319

? matches a single character, * matches any number of characters (even none). Since you're looking to match any name that includes Z1, the expression you need is this:

files = glob.glob('Z:/{}/{}/DL/*Z1*.txt.bz2'.format(directory, folder))

Mind you, this will also match anything like

Z1_Y1_B.txt.bz2
2407Z1_124607_1000_Y1_B.txt.bz2
2407Z1_124607_1000_X1_Z1.txt.bz2
etc.

As long as there's a Z1 in there before the .txt.bz2 and after the last slash, it will match

Upvotes: 1

Related Questions