Partial directory search question

Tim Chase python.list at tim.thechases.com
Wed Sep 30 13:00:26 CEST 2009


> import os
> 
> for filename in os.listdir("/usr/bbs/confs/september"):
>      #stat = os.stat(filename)
>      if filename.startswith("_"):
>         print filename

yes, as lallous mentioned, this can be done as a 
list-comprehension/generator.  If printing is all you want to do, 
it's a nice and concise way:

  print '\n'.join(fname for fname in os.listdir(loc) if 
fname.startswith('_'))

If you're doing more processing than just printing it, your 
for-loop is a better (clearer) way to go.  If you have lots of 
processing code, it might help to do the inverse:

   for filename in os.listdir(location):
     if not filename.startswith('_'): continue
     lots()
     of_processing()
     and_your_complex_logic()
     goes()
     here()

It removes one level of indentation depth and makes it clear that 
you don't intend to do anything with the non-leading-underscore 
versions (rather than looking for a corresponding "else:" line 
possibly screens later).

-tkc







More information about the Python-list mailing list