python - 按排序顺序处理文件
问题描述
我在一个目录中有 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 代码?
解决方案
你可以这样做:
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)
推荐阅读
- javascript - 时间复杂度 - 图
- python - 小时和时间转换为某种格式
- unit-testing - 有没有办法在 Quasar 中使用全局笑话模拟?
- node.js - 节点流:如何转换 Buffer 流以将数组写入输出
- flutter - 共享首选项中的颤振功能
- python - Python:我有一个列表,我想将它添加到列表的每个元素中
- sql - 行存储功能上的 Sql Server 2019 批处理模式不起作用
- scala - 将 Spark DataFrame 导出到 S3
- awk - Bash - awk 函数是否具有内置的 julian day 函数?
- json - 如何将以下 json 解组为 golang 结构