soccer_analytics_fan
soccer_analytics_fan

Reputation: 319

How to go through files in directory in ascending order

I currently have a certain file in my directory that I am going through in Python and iterating using os.listdir.

The files in this directory are stored as numbers like this:

36 51 72 117 138 255 . . . . 1095 2000 3001 4004

Instead of iterating in this order, the files iterate according to the first number in the file. So instead of going ascending order it would go 1095->2000->3001->36->5001->51 and so on. How can I ensure that I iterate in the correct ascending order?

Upvotes: 3

Views: 2166

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use sorted:

sorted(os.listdir('path/to/dir'), key=int)

To ensure that the order is numerical do key=int. The function os.listdir returns a list, to iterate over them just do:

for files in sorted(os.listdir('path/to/dir'), key=int)

Upvotes: 3

C. Fennell
C. Fennell

Reputation: 1032

I assume you have your file names stored in a list for iterating over, if you do, all you have to do is:

fileList.sort()

then iterate over it as you have been.

Upvotes: 0

Related Questions