How do you sort files numerically?
        Posted  
        
            by 
                Zachary Young
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Zachary Young
        
        
        
        Published on 2011-01-07T07:34:12Z
        Indexed on 
            2011/01/07
            7:54 UTC
        
        
        Read the original article
        Hit count: 381
        
Hello all,
First off, I'm posting this because when I was looking for a solution to the problem below, I could not find one on stackoverflow. So, I'm hoping to add a little bit to the knowledge base here.
I need to process some files in a directory and need the files to be sorted numerically.  I found some examples on sorting--specifically with using the lamba pattern--at wiki.python.org, and I put this together:
#!env/python
import re
tiffFiles = """ayurveda_1.tif
ayurveda_11.tif
ayurveda_13.tif
ayurveda_2.tif
ayurveda_20.tif
ayurveda_22.tif""".split('\n')
numPattern = re.compile('_(\d{1,2})\.', re.IGNORECASE)
tiffFiles.sort(cmp, key=lambda tFile:
                   int(numPattern.search(tFile).group(1)))
print tiffFiles
I'm still rather new to Python and would like to ask the community if there are any improvements that can be made to this: shortening the code up (removing lambda), performance, style/readability?
Thank you, Zachary
© Stack Overflow or respective owner