pythonpython-2.7sortingos.walknatsort

How to sort folder names with natsort in Python that I got with os.walk?


I am new to Python. I have to crawl trough many folders and check for a specific file. If this file is in this folder the name of the folder will be appended at the end of a list. After that I want the names of the folder to be sorted naturally. I tried natsorted(filename), of the natsort package but somehow it didn't sort the list.

My code:

for dirName, subdirList, fileList in os.walk(folder):
if mat_file in fileList:
    input_path = dirName + r"\file.txt"
    if os.path.isfile(input_path):
        filename.append(str(dirName.strip(folder)))

natsorted(filename)
print filename

folder is the path to the folders

I got:

['1.1', '1.10', '1.2', '1.4', '1.6', '2.1', '2.10', '2.11', '2.12', '2.6']

I want:

['1.1', '1.2', '1.4', '1.6', '1.10', '2.1', '2.6', '2.10', '2.11', '2.12']

Is there a solution to this problem?


Solution

  • Because natsorted like sorted doesn't mutate the list like .sort() would, you need to assign the return value of natsorted(filename) back to the filename variable like:

    filename = natsorted(filename)