Victor
Victor

Reputation: 447

How to form a glob that works for a wild char or exact match?

Iam using a statement such as :

input_stuff = '1,2,3'
glob(folder+'['+ input_stuff + ']'+'*')

to list files that begin with 1,2 or 3 while this lists files such as 1-my-file, 2-my-file, 3-my-file . This doesnt work if exact file names are given

input_stuff = '1-my-file, 2-my-file, 3-my-file'
glob(folder+'['+ input_stuff + ']'+'*')

The error is :sre_constants.error: bad character range

worse for :

input_stuff = '1-my-'
glob(folder+'['+ input_stuff + ']'+'*')

It prints everything in the folder such as 3-my-file etc.,

Is there a glob statement that will print files for both

input_stuff = '1,2,3'

or

input_stuff = '1-my-file, 2-my-file, 3-my-file'

?

Upvotes: 0

Views: 749

Answers (2)

robyschek
robyschek

Reputation: 2035

Glob expression in brackets is a set of characters, not a list of strings. You first expresion input_stuff = '1,2,3' is equivalent to '123,' and will also match a name starting with comma.
Your second expression contains '-', which is used to denote character ranges like '0-9A-F', hence the error you get.

It is better to drop glob altogether, split input_stuff and use listdir.

import re, os

input_stuff = '1-my-file, 2-my-file, 3-my-file'
folder = '.'

prefixes = re.split(r'\s*,\s*', input_stuff) #split on commas with optional spaces
prefixes = tuple(prefixes) # startswith doesn't work with list
file_names = os.listdir(folder)
filtered_names = [os.path.join(folder, fname) for fname in file_names 
                  if file_name.startswith(prefixes)]

Upvotes: 1

Natsukane
Natsukane

Reputation: 681

You can use the following:

input_stuff = '1,2,3'
glob(folder+'['+input_stuff+']-my-file*')

EDIT: Since you said in your comment that you can't hardcode "-my-file", you can do something like:

input_stuff = '1,2,3'
name = "-my-file"
print glob.glob(folder+'['+input_stuff+']'+name+'*')

and then just change the "name" variable when you need to.

Upvotes: 0

Related Questions