Search code examples
pythonsortingdirectoryalphabeticallistdir

Sort files then directories os.listdir PYTHON


I'm trying to sort files and directories in specific way (for me it is usuall way but ok). So I have JPG files, then some txt files or wav and I have some directories I want it sorted like first sort by name all files then sort directories but when I'm trying to do something like :

path = "/my_path"
arr = os.listdir(path)
arr.sort(key=lambda x: (os.path.isdir(x), x))
print(arr)

Code gives me output :

['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'HRYS', 'WAVS', 'k.txt', 's.wav']

but it should be :

['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'k.txt', 's.wav', 'HRYS', 'WAVS']

How to do it in proper way ?


Solution

  • Well, the most straightforward way is to provide an appropriate key, so, you can use:

    arr.sort(key=lambda x: (os.path.isdir(x), x))
    

    The key is a tuple, the first item is os.path.isdir(x), which returns a bool.

    EDIT: So, to make sure this works, do:

    def isdir(path, x):
        path = os.path.join(path, x)
        return os.path.isdir(path)
    
    arr.sort(key=lambda x: (isdir(path, x), x))
    

    Although, it might be easier to use os.scandir, which returns more useful DirEntry objects.

    arr = sorted(os.scandir(), key=lambda x: (x.is_dir(), x.name))