PEP ? os.listdir enhancement

Peter Hansen peter at engcorp.com
Wed Jun 22 13:05:10 EDT 2005


Riccardo Galli wrote:
> I noticed that when I use os.listdir I need to work with absolute paths
> 90% of times.
> While I can use a for cycle, I'd prefere to use a list comprehension,
>  but it becomes too long.
> 
> ### e.g. 1 part 1 - getting a list of directories ### 
> dirs=[]
> for i in os.listdir(path):
>     tmp_path=os.path.join(path,i)
>     if os.path.isdir(tmp_path):
>         dirs.append(tmp_path)
> 
> ### e.g. 1 part 2 ###
> dirs=[join(path,x) for x in listdir(path) if isdir(join(path,x))]

Using Jason Orendorff's "path" module, all this code basically collapses 
down to this beauty (with your variable "path" renamed to myPath to 
avoid a name collision):

from path import path
dirs = path(myPath).abspath().dirs()

-Peter



More information about the Python-list mailing list