3
votes

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?

1

1 Answers

3
votes

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.