gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:55:29 25 4
gpt4 key购买 nike

应该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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com