Reputation: 1836
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?
Upvotes: 3
Views: 1847
Reputation: 1122082
You can use any iterable producing lines, it doesn't just have to be a file object. You can split your string into a list of lines with str.splitlines()
:
for row in csv.DictReader(inputtext.splitlines()):
print row
Demo:
>>> import csv
>>> demostring = '''\
... foo,bar,baz
... 42,Monty,Python
... 38,Ham,Spam
... '''
>>> for row in csv.DictReader(demostring.splitlines()):
... print row
...
{'foo': '42', 'baz': 'Python', 'bar': 'Monty'}
{'foo': '38', 'baz': 'Spam', 'bar': 'Ham'}
Upvotes: 5
Reputation: 369094
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'}
Upvotes: 5