-1

I have a folder in which I have files like 1.jpg, 2.jpg, ... 40.jpg;

root_dir = r'C:\Users\ab\pythonfiles\Compressed_images'
for root, dirs, files in os.walk(root_dir):
    for file in files:
        print(file, '\n')

It prints this

1.jpg
10.jpg
11.jpg
...
19.jpg
2.jpg
20.jpg
...

I want it to read in the order 1.jpg, 2.jpg, 3.jpg, ... ; how can I achieve this?

ab123
  • 203
  • 4
  • 12

1 Answers1

0

Try sorting the files list using sorted.

Ex:

root_dir = r'C:\Users\ab\pythonfiles\Compressed_images'
for root, dirs, files in os.walk(root_dir):
    for file in sorted(files, key=lambda x: int(x.split(".")[0])):
        print('For file: \n', file)
Rakesh
  • 81,458
  • 17
  • 76
  • 113