遍历每个文件(排序),得到4个文件,执行一些python操作。

问题描述 投票:0回答:1

我在一个文件夹里有多个文件,我想让前四个文件执行一些操作,然后让后四个文件执行一些操作,以此类推。但我无法以排序的方式遍历每个文件。我尝试使用 glob.glob,但我不知道如何使用 glob 中的索引来遍历每个文件。

我的文件是 0.jpg 1.jpg 2.jpg 3.jpg 4.jpg......

for image in sorted(glob.glob(directory + '*.jpg'),key=os.path.getmtime):

    name = image.split('/')[-1]
    imgname = name.split('.')[0]
python indexing iterator
1个回答
0
投票

这里有一个方法。我看你有 另一个问题 我建议你创建一个 "填充 "的图像(作为一个 PNG 这样它就不会出现在您的排序列表中。JPEGs). 使 "填充 "图像与你粘贴其他4张图像的背景颜色相同,这样它就不会出现。

#!/usr/bin/env python3

import os, glob
from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    """
    Group items of list in groups of "n" padding with "fillvalue"
    """
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

# Go to where the images are instead of managing a load of paths
os.chdir('images')

# Get list of filenames sorted by mtime
filenames = sorted(glob.glob('*.jpg'),key=os.path.getmtime)

# Iterate over the files in groups of 4
for f1, f2, f3, f4 in grouper(filenames, 4, 'fill.png'):
    print(f1,f2,f3,f4)

输出示例

iphone.jpg door.jpg hands.jpg solar.jpg
test.jpg circuit_board.jpg r1.jpg r2.jpg
thing.jpg roadhog.jpg colorwheel.jpg hogtemplate.jpg
tiger.jpg bean.jpg image.jpg bottle.jpg
result.jpg fill.png fill.png fill.png
© www.soinside.com 2019 - 2024. All rights reserved.