Python sorting files in a folder error
Question: I have a folder where I have names as

    
    
    file_1.txt,file_2.txt,file_3.txt,file_10.txt,file_100.txt.
    

I am reading these files using os.walk.i want print file names in a sorted
order.My code is as follows:

    
    
    import os
    import fnmatch
    rootDir = "lecture1"
    for root, dirs, files in os.walk(rootDir):
       files = sorted(files)
       for file in fnmatch.filter(files, '*.wav'):
            print os.path.join(rootDir, file)
    

But the above code is not printing the file in a sorted order.please suggest
me a way so that i can print it in a sorted order as follows:

    
    
    file_1.txt,file_2.txt,file3_txt,file_10.txt,file_100.txt
    

Currently its printing

    
    
    file_1.txt,file_1.txt,file_100.txt,file_2.txt,file_3.txt
    


Answer: It doesn't sorted the output because

    
    
    files = sorted(files)
    

and files is `file_1.txt`, `file_100.txt`, etc.

But as the above example, `file_1.txt` or `file_100.txt` is string, and
`sorted` thinks that `file_2.txt` > `file_100.txt` because `'2'` > `'1'` (note
that `''`).

To explain this more clear:

    
    
    >>> '2' > '100'
    True
    >>> 2 > 100
    False
    >>> int('2') > int('100')
    False
    >>> 
    

* * *

So you need use regex to get the number, covert it to int use `int()`
function, and then set a sort key like the following code:

    
    
    import os
    import re
    import fnmatch
    
    rootDir = "lecture1"
    
    for root, dirs, files in os.walk(rootDir):
       files.sort(key=lambda x: int(re.search('file_(\d+)\.txt', x).group(1)))
       for file in fnmatch.filter(files, '*.wav'):
            print os.path.join(rootDir, file)
    

