我正在使用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有关吗?
发布于 2019-03-26 12:46:16
这是因为文件是根据它们的名称(即字符串)排序的,并且它们是按字典顺序排序的。有关相关细节的更多排序,请查看[Python.Docs]:如何排序。
要使事情如您所料,“错误”文件9.bmp应该命名为09.bmp (这适用于所有此类文件)。如果您有超过100个文件,事情就会更加清晰(所需的文件名将是009.bmp,035.bmp)。
无论如何,还有一种选择(前提是所有文件的都遵循命名模式),方法是将文件的基名(没有扩展名- check [Python.Docs]:os.path -常见路径名操作)转换为int,并根据它进行排序(提供)键)。
files = sorted(glob.glob("../../Documents/ImageAnalysis.nosync/sliceImage/*.bmp"), key=lambda x: int(os.path.splitext(os.path.basename(x))[0]))发布于 2019-03-26 12:36:19
不是用glob.glob。它根据基础系统的规则返回未排序或排序的列表。
您需要做的是为sorted提供一个合适的键函数,以定义所需的顺序,而不是纯文本字符串。类似于(未经测试的代码):
def mysorter( x):
path, fn = os.path.split( x)
fn,ext = os.path.splitext( fn)
if fn.isdigit():
fnn = int(fn)
fn = f'{fnn:08}' # left pad with zeros
return f'{path}/{fn}.{ext}'然后
results=sorted( glob.glob(...), key=mysorter )https://stackoverflow.com/questions/55357306
复制相似问题