Python's CSV reader
Peter Otten
__peter__ at web.de
Thu Aug 4 03:24:42 EDT 2005
Stephan wrote:
> Can the CSV module be coerced to read two line formats at once or am I
> better off using read and split?
Yes, it can:
import csv
import sys
reader = csv.reader(sys.stdin)
while True:
try:
names = reader.next()
values = reader.next()
except StopIteration:
break
print dict(zip(names, values))
Python offers an elegant way to do the same using the zip() or
itertools.izip() function:
import csv
import sys
from itertools import izip
reader = csv.reader(sys.stdin)
for names, values in izip(reader, reader):
print dict(izip(names, values))
Now let's add some minimal error checking, and we are done:
import csv
import sys
from itertools import izip, chain
def check_orphan():
raise Exception("Unexpected end of input")
yield None
reader = csv.reader(sys.stdin)
for names, values in izip(reader, chain(reader, check_orphan())):
if len(names) != len(values):
if len(names) > len(values):
raise Exception("More names than values")
else:
raise Exception("More values than names")
print dict(izip(names, values))
Peter
More information about the Python-list
mailing list