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

Python实现CSV列名不存在时写入及追加视频信息的问题排查

修复CSV列名未写入的问题

问题根源

原代码存在三个致命问题:

  • 用r模式打开文件时,若文件不存在直接报错;若文件为空,csv.reader的循环不会执行,直接跳过列名写入逻辑
  • 条件判断row[0] in reader is not None语法和逻辑完全错误,根本起不到检查首行的作用
  • 写入列名的逻辑嵌套在循环里,就算触发也会导致逻辑混乱

修正后的代码

import csv
import os
import random

# 预设CSV列名
COLUMNS = ["id", "fileName", "videoName", "description", "genre"]
csv_file = "videos.csv"

# 确保CSV文件存在且首行是列名
file_exists = os.path.exists(csv_file)
if file_exists:
    with open(csv_file, 'r') as f:
        reader = csv.reader(f)
        # 读取第一行,判断是否匹配预设列名
        first_row = next(reader, None)
        if first_row != COLUMNS:
            # 覆盖文件写入列名
            with open(csv_file, 'w', newline='') as f_write:
                writer = csv.writer(f_write)
                writer.writerow(COLUMNS)
else:
    # 文件不存在,创建并写入列名
    with open(csv_file, 'w', newline='') as f_write:
        writer = csv.writer(f_write)
        writer.writerow(COLUMNS)

# 追加视频信息
with open(csv_file, 'a', newline='') as f_append:
    writer = csv.writer(f_append)
    random_id = str(random.randint(1, 1000000))
    file_name = os.path.basename(filePath)  # 注意:filePath需提前定义
    writer.writerow([random_id, file_name, videoName, description, genre])

关键改进点

  • 先判断文件是否存在,避免r模式打开不存在的文件抛出异常
  • 用next(reader, None)直接读取第一行,简洁判断是否是预设列名
  • 写入时添加newline='',解决Windows系统下CSV自动生成空行的问题
  • 拆分逻辑为「确保列名存在」和「追加数据」两步,避免重复打开文件的混乱

内容的提问来源于stack exchange,提问作者Ivan McKenna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:47:11