GLOB.GLOB排序-不像预期的那样 [英] glob.glob sorting - not as expected

查看:111
本文介绍了GLOB.GLOB排序-不像预期的那样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.bmp90.bmp之间有文件9.bmp这显然不应该在那里,应该在开头附近

我期望的输出类型如下:

1.bmp
2.bmp
3.bmp
4.bmp
5.bmp
6.bmp
...
10.bmp
11.bmp
12.bmp
13.bmp
...

依此类推,直到文件结束

这与GLOB有关吗?

推荐答案

这是因为文件根据其名称(即字符串)进行排序,并按词典顺序排序。有关更多与排序相关的详细信息,请查看[Python.Docs]: Sorting HOW TO
要按照您的预期工作,"错误"文件应命名为(这适用于所有此类文件)。如果您有100个以上的文件,情况会更清楚(所需的文件名将是009.bmp)。

无论如何,还有一种替代方法(假设所有文件都遵循命名模式),方法是将文件的基本名称(不带扩展名-check[Python.Docs]: os.path - Common pathname manipulations)转换为int,并基于此进行排序(通过将提供到[Python.Docs]: sorted(iterable, *, key=None, reverse=False))

files = sorted(glob.glob("../../Documents/ImageAnalysis.nosync/sliceImage/*.bmp"), key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))

这篇关于GLOB.GLOB排序-不像预期的那样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆