2

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.

bones225
  • 1,488
  • 2
  • 13
  • 33
  • 1
    Related question: https://apple.stackexchange.com/questions/304983/clean-up-by-name-isnt-sorting-my-files-in-alphabetical-order – bones225 Jun 11 '20 at 21:28
  • Do all the filenames follow a format similar to `[SOME-TEXT][NUMBER].[FILE-ENDING]`? – shmulvad Jun 11 '20 at 21:34
  • 1
    Finder does a "natural sort", which treats numbers in the filename specially. – Barmar Jun 11 '20 at 21:36

1 Answers1

3

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']
chash
  • 3,975
  • 13
  • 29