How to separate directory list and file list?

Alex Martelli aleaxit at yahoo.com
Sun Oct 23 12:43:45 EDT 2005


Gonnasi <harddong at 21cn.net> wrote:

> With
> >glob.glob("*")
> 
> or
> >os.listdir(cwd)
> 
> I can get a combined file list with directory list, but I just wanna a
> bare file list, no directory list. How to get it?

I see everybody's suggesting os.path.* solutions, and they're fine, but
an interesting alternative is os.walk:

__, thedirs, thefiles = os.walk('.').next()

thefiles is the list of filenames (and thedirs is the list of directory
names), and each is sorted alphabetically.  (I'm assigning to '__' the
absolute path of the current directory, meaning I intend to ignore it).
An expression that just provides the filename list is

  os.walk('.').next()[2]

although this may be a tad too obscure to recommend it!-)


Alex



More information about the Python-list mailing list