-1

I have a mainPath to indicate the path to do function listdir(). I want to get the name of the files inside the mainPath. So I tried this:

import os
os.listdir(mainPath)

And I get the following result

enter image description here

However, I would like that the list of paths will be ordered based on the number of each filename. Something like ['01. Enero','02. Febrero', '03. Marzo', ..., '09. Setiembre']. So, how this could be done?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Maria Fernanda
  • 143
  • 2
  • 8
  • 1
    Please include the output of `os.listdir(mainPath)` [as text directly into your question](https://stackoverflow.com/editing-help), do not link or embed external images. Images make it difficult to efficiently assist you as they cannot be copied and offer poor usability as they cannot be searched. See: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/15497888) – Henry Ecker Nov 11 '21 at 03:44
  • 2
    Personally, I'm partial to [natsort](https://github.com/SethMMorton/natsort). Like [this answer](https://stackoverflow.com/a/18415320/15497888) by [SethMMorton](https://stackoverflow.com/users/1399279/sethmmorton). `from natsort import natsorted` then just `results = natsorted(os.listdir(mainPath))` (which will handle all sorting by numbers correctly). Although since the names are already zero padded just `results = sorted(os.listdir(mainPath))` should work fine as well. – Henry Ecker Nov 11 '21 at 03:49
  • One can use this answer for more options on the same: https://stackoverflow.com/questions/25657705/make-os-listdir-list-complete-paths – unityJarvis Nov 11 '21 at 03:53

1 Answers1

1

Please try and assign the result from os.listdir to a list and sort the list. For example


>>>> res = os.listdir(mainPath)
>>>> res
['06. file', '01. file', '02. file', '10. file', '04. file','08. file', '05. file', '07. file',  '09. file', '03. file']
>>>> res.sort()
['01. file', '02. file', '03. file', '04. file', '05. file', '06. file', '07. file', '08. file', '09. file', '10. file']

unityJarvis
  • 379
  • 1
  • 9