[Tutor] Better way - fnmatch with list ?

bob gailer bgailer at gmail.com
Sat Jan 3 00:44:06 CET 2009


Damon Timm wrote:
> Hi - am learning Pythong and loving it!   Anyhow, what I have works,
> but I wondered if there was a "better" (more python-y) way.
>
> Here is what I am doing with fnmatch ... am thinking there has to be a
> one-line way to do this with a lambda or list comprehension ... but my
> mind can't get around it ... I have other code, but the main part is
> that I have a list of files that I am going through to check if they
> have a given extension ... in this part, if the file matches any of
> the extension I am looking for, I want it to do some stuff ... later I
> check it against some other extensions to do "other" stuff:
>
> for file in files:
>     for ext in ['*.flac','*.mp3','*.m4a']:
>         if fnmatch.fnmatch(someFile, ext):
>             #do some stuff if the someFile matches one of the items in the list
>   

Since file is a built-in function it is a good idea to not use it as a 
variable name.

for fn in files:
    base, ext = os.path.splitext(fn)
    if ext in ['*.flac','*.mp3','*.m4a']:
        #do some stuff if the someFile matches one of the items in the list
> Can it get any better ?  I was hoping fnmatch would *accept* a list
> instead of a string ... but it didn't (frown).  I thought maybe:
>
> if fnmatch(someFile, ['*.flac','*.mp3','*.m4a']):
>
> But that didn't work.  Thanks in advance,
>
> Damon
>
> PS: just reading the conversations on this list is a little like
> taking a python class (only the classes don't progress in any
> particular order!).
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
Chapel Hill NC 
919-636-4239



More information about the Tutor mailing list