本文介绍了为什么csv.DictReader跳过空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使设置了 restval
,似乎 csv.DictReader
也会跳过空行.使用以下内容,将跳过输入文件中的空行:
It seems that csv.DictReader
skips empty lines, even when restval
is set. Using the following, empty lines in the input file are skipped:
import csv
CSV_FIELDS = ("field1", "field2", "field3")
for row in csv.DictReader(open("f"), fieldnames=CSV_FIELDS, restval=""):
if not row or not row[CSV_FIELDS[0]]:
sys.exit("never reached, why?")
文件 f
在哪里:
1,2,3
a,b,c
推荐答案
# unlike the basic reader, we prefer not to return blanks,
# because we will typically wind up with a dict full of None
# values
while row == []:
row = self.reader.next()
因此跳过了空行.如果您不想跳过空行,则可以使用 csv.reader
.
So empty rows are skipped.If you don't want to skip empty lines, you could instead use csv.reader
.
另一个选择是将 csv.DictReader
子类化:
Another option is to subclass csv.DictReader
:
import csv
CSV_FIELDS = ("field1", "field2", "field3")
class MyDictReader(csv.DictReader):
def next(self):
if self.line_num == 0:
# Used only for its side effect.
self.fieldnames
row = self.reader.next()
self.line_num = self.reader.line_num
d = dict(zip(self.fieldnames, row))
lf = len(self.fieldnames)
lr = len(row)
if lf < lr:
d[self.restkey] = row[lf:]
elif lf > lr:
for key in self.fieldnames[lr:]:
d[key] = self.restval
return d
for row in MyDictReader(open("f", 'rb'), fieldnames=CSV_FIELDS, restval=""):
print(row)
收益
{'field2': '2', 'field3': '3', 'field1': '1'}
{'field2': '', 'field3': '', 'field1': ''}
{'field2': '', 'field3': '', 'field1': ''}
{'field2': 'b', 'field3': 'c', 'field1': 'a'}
这篇关于为什么csv.DictReader跳过空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!