Search code examples
pythonfinderalphabetical-sort

MacOS Finder sorts alphabetically differently than Python .sort()


I have three files:

x10.txt
x30.txt
x200.txt

If I go to my MacOS finder and sort by name I get the following order:

x10.txt
x30.txt
x200.txt

I am trying to get them in the same order in Python. I am using the following code:

mypath = '/path/to/files/'
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
files.sort()

But get this order:

x10.txt
x200.txt
x30.txt

Is there a way in Python to sort these files in the same order as they appear in Finder? I am wondering if there are multiple different conventions for alphabetical order.


Solution

  • This looks like natural sort order. Numbers are sorted by numerical value, separately from the rest of the string.

    If you're looking for a library, you can use natsort:

    >>> import natsort
    >>> l = ['x10.txt', 'x30.txt', 'x200.txt']
    >>> natsort.natsorted(l)
    ['x10.txt', 'x30.txt', 'x200.txt']