Optimizing tips for os.listdir

Brian Beck exogen at gmail.com
Mon Sep 27 21:09:36 CEST 2004


Thomas wrote:
> I'm doing this :
> 
> [os.path.join(path, p) for p in os.listdir(path) if \
> os.path.isdir(os.path.join(path, p))]
> 

I don't have much time to experiment, but I came up with a method using 
os.walk:

import os
def childdirs(path):
     for root, dirs, files in os.walk(path):
         return [os.path.join(root, name) for name in dirs]

This appears to be about the same speed as your code -- for all I know, 
os.walk could be doing the same exact thing under the hood.  But perhaps 
someone could use this and come up with a one-liner -- as of now I can't 
think of a way to do it properly without containing it in a function.

--
Brian Beck
Adventurer of the First Order



More information about the Python-list mailing list