[Tutor] list packing
Kent Johnson
kent37 at tds.net
Mon Feb 27 12:25:50 CET 2006
kevin parks wrote:
> John,
>
> Thanks... i am liking this variation a tad more since it means i only
> have to type the path in one place .... but it is akin to your second
> one... i was (still am really) having a hard time understanding
> how to apply path.join _and_ listdir .... sometimes list comprehensions
> twist my brain but this one is worth studying ...
>
> nice! two little lines that do a boatload of work! hee hee
>
> ----
> pth = '/Users/kpp9c/snd/01'
> samples = [os.path.join(pth, f) for f in os.listdir(pth) if f.endswith
> ('.aif')]
> ----
>
> i could even add:
> samples = [os.path.join(pth, f) for f in os.listdir(pth) if f.endswith
> ('.aif' & f.startswith('t')]
You might like Jason Orendorff's path module. Using it you can write
import path
pth = path.path('/Users/kpp9c/snd/01')
samples = list(pth.walkfiles('t*.aif'))
path.walkfiles() returns an iterator, that is why the list() call is
needed. If you are going to loop over the samples you can omit it:
for sample in pth.walkfiles('t*.aif'):
...
http://www.jorendorff.com/articles/python/path/index.html
Kent
More information about the Tutor
mailing list