Monday, December 30, 2013

Python csv.reader parsing individual characters vs lines, items

Occasionally I'll run into situations where Python's csv.reader will parse a file or stream as individual characters vs line by line resulting in the reader, when read from later to look like:

['f']
['o']
['o']
['b']
['a']
['r']

versus the expected:

['foo']
['bar']

Apparently this occurs when the reader is fed a non-iterable (e.g. a string - even though the string has line breaks). This has happened on a few occasions where I've been accepting some web service CSV response.

A more detailed explanation resides here, but in short, simply use .splitlines() on the web service csv and the reader should be able to iterate properly afterward.

No comments:

Post a Comment