Can you use csv.DictReader without a file?

csv, python, python-2.7

Solution

You can use `StringIO` (or `io.BytesIO` / `io.StringIO`):

>>> import StringIO
>>> import csv
>>>
>>> f = StringIO.StringIO(u'''field1,field2,field3
... 1,2,3
... 4,5,6
... 7,8,9
... ''')
>>>
>>> for row in csv.DictReader(f):
...     print row
...
{'field2': '2', 'field3': '3', 'field1': '1'}
{'field2': '5', 'field3': '6', 'field1': '4'}
{'field2': '8', 'field3': '9', 'field1': '7'}

Problem

I have some comma-separated input I want to parse into a dictionary, so `csv.DictReader` seemed like a good fit. However, the input is already in string form and not a file as the interface to `csv.DictReader` wants. Is there a way to use `csv.DictReader` directly with a string?

Original source