首页 > 解决方案 > 按排序顺序处理文件

问题描述

我在一个目录中有 67 张图像,名称为:

Im_2601_0 Im_2601_1 Im_2601_4 Im_2601_8 Im_2601_16 Im_2601_32 Im_2601_64 Im_2601_128 Im_2601_256

Im_2602_0 Im_2602_1 Im_2602_4 Im_2602_8 Im_2602_16 Im_2602_32 Im_2602_64 Im_2602_128 Im_2602_256

Im_2603_0 Im_2603_1 Im_2603_4 Im_2603_8 Im_2603_16 Im_2603_32 Im_2603_64 Im_2603_128 Im_2603_256
.
.
.
.
.
.
.
.
.
Im_26067_0 Im_26067_1 Im_26067_4 Im_26067_8 Im_26067_16 Im_26067_32 Im_26067_64 Im_26067_128 Im_26067_256

文件为 jpg 文件 Im_260x_y 其中 x 为图像数量 1..67,y 为 0、1、4、8、16、32、64、128、258。这些文件随机存储在目录中。

我想按排序顺序处理文件(与我在上面写的顺序相同,即图像 1 用于所有 0、1、4、8、16、32、64、128、258。然后图像 2 用于所有 0、1 , 4, 8, 16, 32, 64, 128, 258 等等)。

我该如何为此编写 Python 代码?

标签: pythonfilesortingdirectory

解决方案


你可以这样做:

from glob import glob
from os import path

DIRECTORY = '.' # directory containing image files
PREFIX = '260'

def process(filename):
    print(filename) # do your real processing here

def getkey(s):
    t = path.basename(s).split('_')
    assert len(t) == 3
    assert t[1].startswith(PREFIX)
    a = t[1][len(PREFIX):]
    b, _ = path.splitext(t[2])
    try:
        return int(a), int(b)
    except ValueError:
        return 0, 0


filelist = glob(path.join(DIRECTORY, 'Im_*'))

for file in sorted(filelist, key=getkey):
    process(file)

推荐阅读