循环文件名的问题 - 读取文件名,如:1,10,100而不是1,2,3

时间:2018-02-15 21:41:30

标签: python-3.x

我在循环浏览文件名时发现了一个有趣的问题。我的代码,如下所示,正在迭代一个带有数字的文本文件,它还循环遍历名为img_test_1.bmp, img_test_2.bmp, img_test_2.bmp的.jpg文件等等(参见下面的完整列表)。我虽然得到了输出img_test_1.bmp, img_test_10.bmp, img_test_100.bmp,依此类推。

我的代码:

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')

实际输出:

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

期望的输出:

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

..等等

可能是什么问题?我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:0)

用零填充文件名。 001.bmp .. 100.bmp将正确排序。