0

I have found an interesting problem while looping through file names. My code, as seen below, is iterating through a text file with numbers, it is also looping through trough .jpg files that are named img_test_1.bmp, img_test_2.bmp, img_test_2.bmp and so on (see the complete list below). I am although getting the output img_test_1.bmp, img_test_10.bmp, img_test_100.bmp and so on instead.

My code:

import os
import os.path
import glob

file_list = open("test.txt","r")
files = glob.glob('*.jpg')

with open ('output.txt', 'w') as in_files:
    for eachimg, lines in zip(files, file_list):
         in_files.write("file: " + str(eachimg) + '\n')

Actual output:

file: img_test_1.bmp
file: img_test_10.bmp
file: img_test_100.bmp
file: img_test_1000.bmp
file: img_test_10000.bmp
file: img_test_10001.bmp
file: img_test_10002.bmp
file: img_test_10003.bmp
file: img_test_10004.bmp
file: img_test_10005.bmp
file: img_test_10006.bmp
file: img_test_10007.bmp
file: img_test_10008.bmp
file: img_test_10009.bmp
file: img_test_1001.bmp
file: img_test_10010.bmp
file: img_test_10011.bmp
file: img_test_10012.bmp
file: img_test_10013.bmp
file: img_test_10014.bmp
file: img_test_10015.bmp
file: img_test_10016.bmp
file: img_test_10017.bmp
file: img_test_10018.bmp
file: img_test_10019.bmp
file: img_test_1002.bmp
file: img_test_10020.bmp
file: img_test_10021.bmp
file: img_test_10022.bmp

Desired output:

file: img_test_1.bmp
file: img_test_2.bmp
file: img_test_3.bmp

..and so on

What could be the issue? How could I fix this problem?

Cœur
  • 37,241
  • 25
  • 195
  • 267
E.W
  • 47
  • 1
  • 7
  • `glob()` uses `os.listdir()` and that function returns filenames as listed by the OS, **without any sorting**. They are not returned in sorted order, and you don't do any sorting yourself. You'd need to use an explicit [natural sort](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort). – Martijn Pieters Feb 15 '18 at 21:48

1 Answers1

0

Pad the file names with zeros. 001.bmp .. 100.bmp will sort properly.

Luke Mlsna
  • 468
  • 4
  • 16