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

如何用Python检查CSV文件并补充缺失的表头

解决CSV表头补全及数据对齐问题

实现思路

  • 先定义完整的目标表头列表(第一个固定为Location,其余5个替换成你的实际表头名)
  • 读取原CSV文件,提取现有表头和数据行
  • 对比找出缺失的表头,将其追加到现有表头末尾
  • 为每一行数据补充对应缺失列的默认值(0或空字符串,按需选择)
  • 将补全后的表头和数据写入新的CSV文件

代码实现

import csv

# 替换成你的完整目标表头,第一个必须是Location,后面5个按实际需求填写
FULL_HEADERS = ["Location", "Sales", "Profit", "Cost", "Inventory", "CustomerCount"]
DEFAULT_VALUE = 0  # 缺失列的填充值,也可以换成""空字符串

# 替换成你的输入输出文件路径
input_file = "source.csv"
output_file = "completed.csv"

with open(input_file, mode='r', newline='', encoding='utf-8') as infile:
    reader = csv.DictReader(infile)
    existing_headers = reader.fieldnames
    data_rows = list(reader)

# 筛选出缺失的表头,保持目标表头的原有顺序
missing_headers = [header for header in FULL_HEADERS if header not in existing_headers]
new_headers = existing_headers + missing_headers

# 为每行数据补充缺失列的默认值
for row in data_rows:
    for header in missing_headers:
        row[header] = DEFAULT_VALUE

# 写入补全后的CSV文件
with open(output_file, mode='w', newline='', encoding='utf-8') as outfile:
    writer = csv.DictWriter(outfile, fieldnames=new_headers)
    writer.writeheader()
    writer.writerows(data_rows)

关键说明

  • 表头顺序:保留原CSV中已存在的表头顺序,缺失的表头会按FULL_HEADERS里的顺序追加到末尾
  • 编码适配:如果你的CSV包含中文,可根据实际编码调整encoding参数(比如gbk)
  • 填充值灵活切换:把DEFAULT_VALUE改成""即可用空值填充缺失列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:15:44