sort by file/directory

Peter Hansen peter at engcorp.com
Wed Sep 10 14:55:26 EDT 2003


Mike Zupan 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

For the above list, executing .sort() would give the correct
result, but presumably you meant for this to work in a more
general manner.

Here's one way to do it, using the Decorate-Sort-Undecorate
pattern that should be familiar to all Python programmers:

(Untested code... likely to have various small errors, left
as an exercise for the reader. :-)

# best to avoid using the name "list" as it conflicts with
# a name in the built-in module
names = [ fill in your own data here ]

import os
sortme = []
for name in names:
    # only works if names are absolute, or in current directory
    # you probably have some other way to tell whether 
    # something is a folder, but the key thing is to 
    # form a tuple with 0 for directories, 1 for files, then
    # the name
    sortme.append((not os.path.isdir(name), name))

sortme.sort()    # in-place sort, of course!

# remove "decoration" which forced the sort to put directories
# first, leaving just the names
names = [item[1] for item in sortme]

-Peter




More information about the Python-list mailing list