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

Python读取CSV列名失败 GitLab流水线报KeyError: 'Names'问题

问题:CSV解析抛出KeyError: 'Names',本地正常但GitLab流水线失败

我用以下Python代码提取CSV单列数据,本地VM运行正常,但GitLab流水线中执行时抛出KeyError: 'Names':

import csv

# 读取test.csv文件
with open('test.csv', 'r') as csv_file:
    reader = csv.DictReader(csv_file)
    data = [row['Names'] for row in reader]
print(data)

test.csv仅含一列数据,内容如下:

Names
John
Mary
Smith
paul

预期输出:

['John', 'Mary', 'Smith', 'paul']

同时,在GitLab仓库中打开该CSV文件时,会提示:

无法自动检测分隔符;默认使用","
(原提示:Failed to render the CSV file for the following reasons: Unable to auto-detect delimiter; defaulted to ",")


原因

问题根源是CSV分隔符的自动检测差异。你的CSV是无列分隔符的单列格式,本地环境的csv模块能正确识别,但GitLab的解析器和流水线环境中的csv模块误判了分隔符,导致表头Names未被正确识别,最终触发KeyError。

解决方法

方法1:强制指定分隔符

给DictReader指定一个数据中不存在的分隔符(比如'|'),确保单列数据被正确解析:

import csv

with open('test.csv', 'r') as csv_file:
    reader = csv.DictReader(csv_file, delimiter='|')
    data = [row['Names'] for row in reader]
print(data)

方法2:改用csv.reader读取

如果不需要字典格式,直接用csv.reader跳过表头后读取每行的第一个元素,逻辑更简单:

import csv

with open('test.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    next(reader)  # 跳过表头行
    data = [row[0] for row in reader]
print(data)

方法3:修改CSV格式(可选)

给每行末尾添加逗号,明确列分隔符,让GitLab和解析器都能正确识别:

Names,
John,
Mary,
Smith,
paul,

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:50:43