7

I'm new in Python and I'm working on a script that reads all the files in a directory (which contains only files). I know that I can get the files using a loop like this:

for file in os.listdir("my directory"):

Or a list of files using this syntax:

files = [f for f in os.listdir("my directory ")]

The problem is that I get the files in a completely random order. I solved my problem using a sort command to get my list sorted, but, I am still left wondering:

How does Python sort the files that are returned by the listdir method?

Annapoornima Koppad
  • 1,376
  • 1
  • 17
  • 30
Tiago De Gaspari
  • 98
  • 1
  • 1
  • 9

1 Answers1

7

This question has been addressed on SO, for example, here: Nonalphanumeric list order from os.listdir() in Python

Looks like Python returns the order that the native filesystem uses, and you have to sort them afterwards.

Community
  • 1
  • 1
user3450049
  • 825
  • 1
  • 10
  • 20
  • So it is not completely random. It didn't make sense to me. It's more logical if the method uses the date of the file or its location on disk to return the list. – Tiago De Gaspari May 16 '16 at 02:47
  • Usually filesystems reuse entries on their internal structures to store data of new ones. Mostly what they are returning (and `os.listdir()` giving) is the data the way is in fact stored in the device. – Piranna Jan 24 '17 at 18:11
  • Does this mean that the order is deterministic? Or will some reindexing of the file system yield a different order? –  Jul 19 '19 at 09:40