filter in for loop

Chris cwitts at gmail.com
Thu Aug 28 07:10:25 EDT 2008


On Aug 28, 12:20 pm, GHZ <geraint.willi... at gmail.com> wrote:
> I would like to say something like:
>
> for x in l if <expression>:
>     <do something>
>
> e.g.
>
> for filename in os.listdir(DIR) if filename[-4:] == '.xml':
>     <do something>
>
> instead of having to say:
>
> for filename in os.listdir(DIR):
>     if filename[-4:] == '.xml':
>         <do something>
>
> or
>
> for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'):
>     <do something>
>
> is there a shortcut I'm missing?

from glob import glob
from os import path
DIR = 'PathToFiles'
EXT = '*.xml'

for filename in glob(path.join(DIR, EXT)):
    print filename




More information about the Python-list mailing list