David542
David542

Reputation: 110432

Accounting for lower and uppercase in glob

I need to pass an extension to function, and then have that function pull all files with that extension in both lower and uppercase form.

For example, if I passed mov, I need to function to do:

videos = [file for file in glob.glob(os.path.join(dir, '*.[mM][oO][vV]'))] 

How would I accomplish the lower + upper combination above given a lowercase input?

Upvotes: 4

Views: 4925

Answers (4)

wilson
wilson

Reputation: 177

If you are running this on Unix, you can try to call this:

from subprocess import Popen, PIPE

#replace the "/tmp/test/" and "*.test" with your search path and extension
args = ["find", "/tmp/test/", "-iname", "*.test"]
files = Popen(args, stdout=PIPE).stdout.readlines()

>>> files
['/tmp/test/a.Test\n', '/tmp/test/a.TEST\n', '/tmp/test/a.TeST\n', '/tmp/test/a.test\n']

more detail on subprocess

Upvotes: 0

aaren
aaren

Reputation: 5685

You can convert strings between upper and lowercase easily:

>>> ext = 'mov'
>>> ext.upper()
'MOV'

So just use that in your function.

Upvotes: 1

Nolen Royalty
Nolen Royalty

Reputation: 18653

Something like this?

>>> def foo(extension):
...     return '*.' + ''.join('[%s%s]' % (e.lower(), e.upper()) for e in extension)
... 
>>> foo('mov')
'*.[mM][oO][vV]'

Upvotes: 6

zigdon
zigdon

Reputation: 15073

Since glob just calls os.listdir and fnmatch.fnmatch, you could just call listdir yourself, and do your own matching. If all you're looking for is a matching extension, it's a pretty simple test, and shouldn't be hard to write either as a regular expression or with [-3:]

Upvotes: 5

Related Questions