Python - order of os.listdir

16,844

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.

Share:
16,844
Tiago De Gaspari
Author by

Tiago De Gaspari

By day: Work at Eldorado Research Institute with C++, computer vision and deep learning. By Night: Trying to write some cool stuff.

Updated on July 11, 2022

Comments

  • Tiago De Gaspari
    Tiago De Gaspari almost 2 years

    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?

  • Tiago De Gaspari
    Tiago De Gaspari about 8 years
    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.
  • Piranna
    Piranna over 7 years
    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.
  • EmielBoss
    EmielBoss almost 5 years
    Does this mean that the order is deterministic? Or will some reindexing of the file system yield a different order?