Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MacOS Finder sorts alphabetically differently than Python .sort() [duplicate]

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.

like image 922
bones225 Avatar asked Jan 29 '26 20:01

bones225


1 Answers

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']
like image 164
chash Avatar answered Jan 31 '26 11:01

chash