Dumb glob question

Python Dunce PDunce at somewhere.invalid
Tue Feb 8 20:18:59 EST 2005


Michael Hoffman <cam.ac.uk at mh391.invalid> wrote in comp.lang.python:

> Python Dunce wrote:
> 
>> So if I happen 
>> to be processing 'foo [bar].par2'
>> 
>> glob.glob(filename[:-5]+'.*par2')
>> 
>> doesn't return anything.  Using
>> win32api.FindFiles(filename[:-5]+'.*par2') works perfectly, but I don't
>> want to rely on win32api functions.  I hope that made more sense :).
> 
> If you look in the source for glob.py, you will find that it calls the
> fnmatch module, and this is the docstring for fnmatch.translate():
> 
>      """Translate a shell PATTERN to a regular expression.
> 
>      There is no way to quote meta-characters.
>      """
> 
> So you cannot do what you want with glob.
> 
> You can replace [] with ? in your glob string, if you are sure that
> there won't be other characters there. That's a bit of a hack, and I
> wouldn't do it.
> 
> In my mind it would probably be best to do:
> 
> re_vol = re.compile(re.escape(startpart) + ".*vol.*")
> lst = [filename for filename in os.listdir(".") if
> re_vol.match(filename)] 
> 
> I changed "list" to "lst" because the former shadows a built-in.

Thanks, that should do the trick!  I had tried basically the same thing 
once but I was getting back empty lists.  I think it was just a brain fart 
involving a case sensitive regex that didn't match the files I was testing 
it on :/.



More information about the Python-list mailing list