0

I am trying to read all files in a specific directory using os.listdir in python in Ubuntu. But the files are not alphabetically sorted just like Windows does. The weird thing is that it doesn't even read all files started with 'o' then go for 'j' then 'z'. It seems like totally random. And the same goes with files named only with numbers like it reads first '67.png' then '76.png' then '71.png'... I'm new to Linux so maybe unlike Windows it sorts them in another way like based on HEX.

I would appreciate if anyone helps me find out the reasoninng behind this apparent disorder.

Hamed
  • 93
  • 6
  • 1
    Is [because the documentation says so](https://docs.python.org/3/library/os.html?highlight=os%20listdir#os.listdir) sufficient? "The list is in arbitrary order, and does not include the special entries '.' and '..'" So it's fully by design and you are free to sort in whatever order you think is useful. – Jongware Mar 06 '20 at 19:16
  • 1
    See this question: https://stackoverflow.com/questions/8977441/does-readdir-guarantee-an-order – Lorenz Mar 06 '20 at 19:20
  • Yes you are right but why using this funtion to read files and folders in Windows returns an alphabetically sorted list of files and folders? – Hamed Mar 06 '20 at 19:42
  • 1
    Because Windows does that, not Python. All the documentation says is you should not *count* on it. If your code works on Windows and you are sure it won't ever need adjusting for a wider audience, then just let it go. – Jongware Mar 06 '20 at 20:10

0 Answers0