sort by file/directory

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Sep 10 15:40:14 EDT 2003


>>>>> "Mike" == Mike Zupan <mzupan at meso.com> writes:

    Mike> I have a list that includes files and directories ie: list =
    Mike> ['file', 'file2', 'dir1','file3','dir2' ]

    Mike> I want to sort it so it looks like this

    Mike> ['dir1', 'dir2', 'file1','file2','file3' ]


    Mike> I'm just wondering if there is an easy way to do this


This is a good example of when you should use the decorate, sort,
undecorate (DSU) pattern.  When python sorts tuples, it compares first
on the first element of the tuple and then on the next element, and
then so on.  If you create tuples where the first element of dirs
compares less than the first element of files, and the second element
is just the dir/file name, then you'll get the sort you want.  All you
have have to do is undecorate, ie, remove the unwanted information
from the tuples.  Here is the approach

    import os
    fnames = ('emacs', '.emacs', 'tex','.tcshrc','diary' )

    tmp = [ (not os.path.isdir(fname), fname) for fname in fnames] # decorate
    tmp.sort() # sort
    fnamesSorted = [fname for isdir, fname in tmp] # undecorate

For more info on DSU, see
http://groups.google.com/groups?num=20&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&q=dsu+group%3A*python*&btnG=Google+Search
and the Python Cookbook, which has a chapter on sorting mainly devoted
to DSU.

    Mike> list = ['file', 'file2', 'dir1','file3','dir2' ]

You may want to avoid the name list because it is a built-in.  For
example, to convert a string to a list of characters, you would do

    seq = list('John Hunter')

After creating a variable named list, you can no longer do this.


Cheers,
John Hunter





More information about the Python-list mailing list