Where do extra fields go when a CSV row is wider than its header?

DictReader collects surplus fields under restkey and fills missing columns in short rows with restval.

Python example and interpretation

One row has a surplus tail and another lacks its label. Recording both conditions prevents schema drift from masquerading as valid data.

import csv
list(csv.DictReader(['id,tag','1,a,tail','2'],restkey='_extra',restval=None))

Result [{'id': '1', 'tag': 'a', '_extra': ['tail']}, {'id': '2', 'tag': None}]

中文

一行 CSV 比表头多出字段时,多余值去了哪里?

DictReader 可把超出表头的值放在 restkey 下,较短记录的缺列由 restval 填充。

Python 算例与适用条件

两条记录一条多出 tail,一条缺少标签。分别记录两种异常,能避免把列错位误当正常样本。

import csv
list(csv.DictReader(['id,tag','1,a,tail','2'],restkey='_extra',restval=None))

结果 [{'id': '1', 'tag': 'a', '_extra': ['tail']}, {'id': '2', 'tag': None}]

References / 参考来源

Keep reading / 继续阅读