You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环仅处理前7张图片问题求助(附代码)

问题排查与解决:Python循环仅处理前7张图片

问题原因

你的代码存在三个关键问题,导致出现“仅处理前7张”的假象(实际所有图片都被遍历了,但CSV文件被反复覆盖,且每张图片被重复写入7次):

  • CSV文件重复覆盖:每次循环处理图片时都用w模式打开CSV,会清空之前的内容,最终仅保留最后一张图片的数据。
  • 内部循环错误:for data in data:是遍历你定义的7元素元组(filename, mode, size, height, width, format, info),导致每张图片被重复写入7次,而非1次。
  • 序号重置:no = 0放在外部循环内,每次处理新图片时序号都会重置为0,无法实现全局递增的序列号。

修正后的代码

from PIL import Image
import glob
import csv

path = r"C:\Users\Hp\Untitled Folder\dataset\sunset*"
# 初始化全局序号
no = 0

# 打开CSV文件,仅执行一次
with open('su_image_scraping_.csv', 'w', newline='') as csvfile:
    fieldnames = ['Serial No.', 'path', 'mode', 'height', 'width', 'format', 'info']
    thewriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
    thewriter.writeheader()

    # 遍历所有图片文件
    for file in glob.glob(path):
        no += 1
        a = Image.open(file)
        # 写入当前图片的一条记录
        thewriter.writerow({
            'Serial No.': no,
            'path': a.filename,
            'mode': a.mode,
            'height': a.height,
            'width': a.width,
            'format': a.format,
            'info': a.info
        })
        print(f"已处理第 {no} 张图片:{a.filename}")

修改说明

  1. 将CSV文件的打开操作移到外部循环之前,确保只创建一次文件并写入表头,避免重复覆盖。
  2. 移除多余的内部循环,直接为每张图片写入一行数据。
  3. 将no的初始化移到外部循环外,每次处理图片时递增,实现连续的序列号。
  4. 优化打印信息,显示当前处理的图片序号和路径,方便跟踪进度。

内容的提问来源于stack exchange,提问作者Divyanshi Agrawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:11:07