pythonnatsort

Python: How to get the same sorting order as Windows file name sorting?


I want to sort filename in python like Windows. I prepare four files(or folders).

1. [abc]abc【abc】
2. [abc]abcabc【abc】
3. 001
4. 002

These are sorted in Windows(ascending order) : 1 -> 2 -> 3 -> 4

But in python, When Using sorted function or natsort(ns.PATH) : 3 -> 4 -> 2-> 1

How to solve this problem?


Solution

  • If you want it in the order that file explorer would put the filenames in by default, then you'll want the folders first and then the files, and both sections in alphabetical order.

    The code below stores all the files in the directory in exactly the same order as file explorer in the list this_dir.

    import os
    
    folder_path = "C:\\Path\\To\\Your\\Folder"
    
    files = []
    folders = []
    
    for f in os.listdir(folder_path):
        fname = os.path.join(folder_path, f)
        if os.path.isdir(fname):
            folders.append(f)
        if os.path.isfile(fname):
            files.append(f)
    
    this_dir = folders + files
    
    
    print("\n".join([" - " + f for f in this_dir]))
    

    Output:

     - abc
     - abcabc
     - 001.txt
     - 002.txt
     - abc.txt
     - abcabc.txt
    

    This is the same order in which file explorer lists them. (abc and abcabc are both folders)