【发布时间】:2019-08-16 20:17:48
【问题描述】:
我正在使用 glob.glob 从目录中读取一些文件,这些文件的名称如下:1.bmp
文件/名称以这种命名模式继续:1.bmp, 2.bmp, 3.bmp ... 等等
这是我目前拥有的代码,但是虽然从技术上讲这确实排序,但它并不像预期的那样。
files= sorted(glob.glob('../../Documents/ImageAnalysis.nosync/sliceImage/*.bmp'))
这个方法是这样排序的:
../../Documents/ImageAnalysis.nosync/sliceImage/84.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/85.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/86.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/87.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/88.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/89.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/9.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/90.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/91.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/92.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/93.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/94.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/95.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/96.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/97.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/98.bmp
../../Documents/ImageAnalysis.nosync/sliceImage/99.bmp
在上面的代码中,我确实强调了这个问题,它能够很好地对文件名进行排序,例如 90-99.bmp 完全没问题,但是在 89.bmp 和 90.bmp 之间有文件 9.bmp 这显然不应该在那里并且应该在起点附近
我期待的输出是这样的:
1.bmp
2.bmp
3.bmp
4.bmp
5.bmp
6.bmp
...
10.bmp
11.bmp
12.bmp
13.bmp
...
以此类推,直到文件结束
这可能与 glob 有关吗?
【问题讨论】:
-
您可以要求它根据
sorted(items, key=lambda x: int(re.findall(r'\d+', x)[0]))之类的数字进行排序?未经测试! -
@hansolo 谢谢!成功了!