文件系统上的文件未排序。您可以使用sorted() function 自己对生成的文件名进行排序:
for infile in sorted(glob.glob('*.txt')):
print "Current File Being Processed is: " + infile
请注意,您的代码中的 os.path.join 调用是无操作的;只有一个参数,它什么也不做,只是返回原样的参数。
请注意,您的文件将按字母顺序排序,这会将10 放在9 之前。您可以使用自定义键功能来改进排序:
import re
numbers = re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
for infile in sorted(glob.glob('*.txt'), key=numericalSort):
print "Current File Being Processed is: " + infile
numericalSort 函数将文件名中的任何数字拆分,将其转换为实际数字,并返回结果进行排序:
>>> files = ['file9.txt', 'file10.txt', 'file11.txt', '32foo9.txt', '32foo10.txt']
>>> sorted(files)
['32foo10.txt', '32foo9.txt', 'file10.txt', 'file11.txt', 'file9.txt']
>>> sorted(files, key=numericalSort)
['32foo9.txt', '32foo10.txt', 'file9.txt', 'file10.txt', 'file11.txt']