[Tutor] Extracting filenames from a List?

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 22 Jan 2002 00:45:00 +0100


On  0, Troels Petersen <troels.petersen@sveg.se.sykes.com> wrote:
> I have a list containing filenames.
> 
> What I would like to do is to extract all files ending in '.jpg' - the case
> does not matter. Everything ending in '.JpG' should be extracted.
> 
> What is the best way to do this? A Regular expression or..? It should fast
> and something that can be understood by a newbie like me (I need to finish
> the 2 last chapters of 'How to Think Like A Computer Scientist').

Here, I like the list comprehension better than filter(), because filter
needs a lambda definition:

jpgs = [f for f in filelist if f.lower().endswith(".jpg")]

vs

jpgs = filter(lambda f: f.lower().endswith(".jpg"), filelist)

I certainly believe that the functional programming way is much easier to
understand than a for loop, in this case. But that may be because of my
experience. The following is more basic Python, and also avoids string
methods so it should work in old Pythons as well:

import string
jpgs = []
for f in filelist:
   if string.lower(f)[-4:] == ".jpg":
      jpgs.append(f)

I don't know why I'm posting this since others already posted solutions, but
whatever :)

-- 
Remco Gerlich