如何以 Pythonic 的方式检测 CSV 文件中的缺失字段? [英] How do I detect missing fields in a CSV file in a Pythonic way?
问题描述
我正在尝试使用 Python 的 csv
模块(特别是 DictReader
类)解析 CSV 文件.有没有 Pythonic 的方法来检测空字段或缺失字段并抛出错误?
I'm trying to parse a CSV file using Python's csv
module (specifically, the DictReader
class). Is there a Pythonic way to detect empty or missing fields and throw an error?
这是一个使用以下标题的示例文件:NAME、LABEL、VALUE
Here's a sample file using the following headers: NAME, LABEL, VALUE
foo,bar,baz
yes,no
x,y,z
解析时,我希望第二行抛出错误,因为它缺少 VALUE 字段.
When parsing, I'd like the second line to throw an error since it's missing the VALUE field.
这是一个代码片段,它显示了我是如何处理这个问题的(忽略硬编码的字符串......它们只是为了简洁起见):
Here's a code snippet which shows how I'm approaching this (disregard the hard-coded strings...they're only present for brevity):
import csv
HEADERS = ["name", "label", "value" ]
fileH = open('configFile')
reader = csv.DictReader(fileH, HEADERS)
for row in reader:
if row["name"] is None or row["name"] == "":
# raise Error
if row["label"] is None or row["label"] == "":
# raise Error
...
fileH.close()
是否有一种更简洁的方法来检查 CSV 文件中的字段,而无需使用一堆 if
语句?如果我需要添加更多字段,我还需要更多条件,我希望尽可能避免.
Is there a cleaner way of checking for fields in the CSV file w/out having a bunch of if
statements? If I need to add more fields, I'll also need more conditionals, which I would like to avoid if possible.
推荐答案
if any(row[key] in (None, "") for key in row):
# raise error
编辑:更好:
if any(val in (None, "") for val in row.itervalues()):
# raise error
这篇关于如何以 Pythonic 的方式检测 CSV 文件中的缺失字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!