Getting all the *files* from a directory -- A better way??

Alex Martelli aleaxit at yahoo.com
Thu Mar 29 04:10:21 EST 2001


<nanotech at europa.com> wrote in message
news:mailman.985816117.6859.python-list at python.org...
> Thanks to everyone who answered!
>
> Notice that:
>
>   dir="/a/b/c"
>
>   files1=[f for f in os.listdir(dir)
>             if os.path.isfile(f)]
>   files2=[os.path.basename(f) for f in os.listdir(dir)
>                               if os.path.isfile(f)]
>
> would be much "prettier" than:
>
>   files1=[os.path.join(dir,f) for f in os.listdir(dir)
>                               if os.path.isfile(os.path.join(dir,f))]
>   files2=[f for f in os.listdir(dir)
>             if os.path.isfile(os.path.join(dir,f))]
>
> if os.listdir returned the given path prepended -- but oh well!!

So wrap it up...:

def joined_listdir(dir):
    return [os.path.join(dir,f) for f in os.listdir(dir)]

then use your wrapper:

files1 = [f for f in joined_listdir(dir) if os.path.isfile(f)]

etc.


Alex






More information about the Python-list mailing list