low-level csv

Skip Montanaro skip.montanaro at gmail.com
Sun Nov 17 09:50:11 EST 2019


On Sun, Nov 17, 2019 at 7:23 AM Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
>
> This is python 2.6->2.7 and 3.5->3.7
>
> I need to convert a string that is a csv line to a list and vice versa.
> I thought to find functions doing this in the csv module but that doesn't
> seem to be the case.

Take a look at the test cases for the csv module. I'm fairly sure all
the inputs for the tests are actually embedded strings. Basically,
just initialize a StringIO object with your string and pass it to the
csv.reader() call. Here's a quick example from the REPL (Python 3.7):

>>> raw = "a,b,c\r\n1,2,3\r\nhowdy,neighbor!\n"
>>> raw
'a,b,c\r\n1,2,3\r\nhowdy,neighbor!\n'
>>> import io
>>> inp = io.StringIO(raw)
>>> import csv
>>> for row in csv.reader(inp):
...   print(row)
...
['a', 'b', 'c']
['1', '2', '3']
['howdy', 'neighbor!']

Skip


More information about the Python-list mailing list