sort by file/directory

Jeremy Jones zanesdad at
Wed Sep 10 21:26:32 CEST 2003

* Mike Zupan (mzupan at wrote:
> I have a list that includes files and directories
> ie: list = ['file', 'file2', 'dir1','file3','dir2' ]
> I want to sort it so it looks like this
> ['dir1', 'dir2', 'file1','file2','file3' ]
> I'm just wondering if there is an easy way to do this

Is there anything in the name of the files/directories that specified that
it is a file or a directory?  If not, then I wouldn't think so.  When you
are gathering the file and directory listing (maybe you're using os.walk?),
then you could at that time do something like (given a 'dir_list' and a

>>> if os.path.isdir(path_to_file):
...     dir_list.append(os.path.basename(path_to_file))
... else:
...     file_list.append(os.path.basename(path_to_file))

Then sort the lists and concatenate them together:

>>> dir_list.sort()
>>> file_list.sort()
>>> new_list = dir_list + file_list
>>> new_list
['bin', 'etc', 'sbin', 'tmp', '.muttrc', 'htpasswd', 'httpd.conf',

Jeremy Jones

More information about the Python-list mailing list