如何以Pythonic方式检测CSV文件中的缺少字段? [英] How do I detect missing fields in a CSV file in a Pythonic way?
问题描述
我试图使用Python的 csv
模块(特别是 DictReader
类)解析CSV文件。是否有Pythonic方法检测空字段或缺少字段并抛出错误?
这里是一个使用以下标题的示例文件:NAME,LABEL,VALUE
foo,bar,baz
yes,no
x,y,z
解析时,我想要第二行抛出一个错误,因为它缺少VALUE字段。
这里是一个代码片段,显示我如何处理这个(忽略硬编码的字符串...他们只是为了简洁):
import csv
HEADERS = [name,label,value]
fileH = open('configFile')
reader = csv.DictReader(fileH,HEADERS)
读取器中的行:
如果row [name]为无或row [name] ==:
#raise错误
如果row [label]为无或row [label] ==:
#raise错误
...
fileH。 close()
有一个更清洁的方法检查CSV文件中的字段,束
如果
语句?如果我需要添加更多的字段,我还需要更多的条件,如果可能,我想避免。解决方案$ p>
如果有的话(row [key] in(None,)for key in row):
#raise error
编辑:更好:
如果有的话(对于row.itervalues()中的val的(无,)的val):
#raise error
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?
Here's a sample file using the following headers: NAME, LABEL, VALUE
foo,bar,baz
yes,no
x,y,z
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()
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
Edit: Even better:
if any(val in (None, "") for val in row.itervalues()):
# raise error
这篇关于如何以Pythonic方式检测CSV文件中的缺少字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!