python - DictReader 应该在错误的列数上出错

标签 python csv

应该Dialect.strictDictReader 上,如果一行中的列数与标题列数不匹配,它会引发异常吗?

The docs (强调我的):

To make it easier to specify the format of input and output records, specific formatting parameters are grouped together into dialects. A dialect is a subclass of the Dialect class having a set of specific methods and a single validate() method. When creating reader or writer objects, the programmer can specify a string or a subclass of the Dialect class as the dialect parameter. In addition to, or instead of, the dialect parameter, the programmer can also specify individual formatting parameters, which have the same names as the attributes defined below for the Dialect class.

Dialect.strict
When True, raise exception Error on bad CSV input. The default is False.

我将其解释为我可以在 DictReader 上设置 strict=True 并让它引发 Error 如果任何行与标题行中的字段数不匹配。

我的代码:test.py

import csv
from pathlib import Path

path = Path('mal.csv')
with path.open(newline="") as f:
    csv_reader = csv.DictReader(f, strict=True)
    for line in csv_reader:
        print(line)

我的 csv:mal.csv

This,Has,many,columns,of,text
This,misses,some
This,has,the,right,number,here
And,here,there,are,too,many,columns,sure,

python ./test.py 不会引发错误并正确打印出行。我怎样才能让它出错?

最佳答案

根据@juanpa.arrivillaga 的评论,我猜 strict 没有达到我的预期,我更改了我的代码以通过检查 如果有任何缺失值则手动引发错误.values() 中的 None(因为像 ,,,\r\n 这样的空项目被编码为空字符串):

import csv
from pathlib import Path

path = Path('mal.csv')
with path.open(newline="") as f:
    csv_reader = csv.DictReader(f, strict=True)
    for line in csv_reader:
        if None in line.values() or None in line.keys():
            raise csv.Error(f"Missing or extra values on line {line}")
        print(line)

我还尝试将 DictReader.restval 更改为 raise 异常的函数或 lambda,但这并没有按照我想要的方式工作。

关于python - DictReader 应该在错误的列数上出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65333170/

相关文章:

python - 在 python 中转义子进程调用的正确方法

python - 如何在 GEKKO GUI 中显示解决方案?

python - 自动数学方程生成器无法正确显示

parsing - 将 CSV 文件转换为在 Lua 中定义键的表

Python - 以特定方式将制表符分隔文件转换为 csv

Python设置不存在的数组的值默认为0

ruby - 如何在 Ruby 中将字符串保存到 CSV 文件?

python - 我的家庭作业有问题。这是关于停止循环

Python复制数组而不进行就地替换

c++ - 在myfile中未在此范围内声明