0

I am trying to loop through the files in a folder with python. I have found different ways to do that such as using os package or glob. But for some reason, they don't maintain the order the files appear in the folder. For example, my folder has img_10, img_20, img_30... But when i loop through them, my code reads the files like: img_30, img_10, img_50... and so on.

I would like my program to read the files as they appear in the folder, maintaining the sequence they are in.

martineau
  • 119,623
  • 25
  • 170
  • 301
Samiur Rahman
  • 63
  • 1
  • 6
  • 1
    That depends on how your OS is sorting them. If your OS is sorting by name or date you could sort it like that in python – Jacques Aug 24 '20 at 10:27

2 Answers2

0

According to this post: Non-alphanumeric list order from os.listdir()

The order you get the files depends on our file system. So either you can write your own sorting function which sorts the file names in the way you want.

Or use the inbuild sorted() method which sorts the file in lexicographic order:

sorted(os.listdir(whatever_directory))

If you want directory sorted by number than as I mentioned you would need to write your sorting function. Something like:

filelist = os.listdir(whatever)
sorted(filename, key= lambda x: int(x[4:]))

NOTE: The above code assumes that your filenames are in format img_1, img_2, img_10 and so on.

Henil
  • 79
  • 1
  • 5
0

My solution would be to use myFiles= os.listdir('directory') And then use myFiles.sort() to sort them. The sort function would sort them in alphabetical order.

Nalin Angrish
  • 317
  • 5
  • 17