Parse a single CSV string?

Viewed 37399

Is there a way that I can parse a single comma delimited string without using anything fancy like a csv.reader(..) ? I can use the split(',') function but that doesn't work when a valid column value contains a comma itself. The csv library has readers for parsing CSV files which correctly handle the aforementioned special case, but I can't use those because I need to parse just a single string. However if the Python CSV allows parsing a single string itself then that's news to me.

4 Answers
>>> import csv
>>> s = '"Yes, this line",can be, parsed as csv'
>>> list(csv.reader([s]))[0]
['Yes, this line', 'can be', ' parsed as csv']
>>>

Basically just @larsks answer above but more brief and demonstrating that it works on csv values that have commas inside quotes.

If you upvote me, upvote the other answer too. https://stackoverflow.com/a/35822856/1196339

String to Pandas DataFrame:

import pandas as pd
from io import StringIO

csv_str="Column1,Column2\n1,2\n3,4"

buff = StringIO(csv_str)
df = pd.read_csv(buff)

DataFrame:

Out[1]: 
   Column1  Column2
         1        2
         3        4

For other delimiters add something like delimiter="\t" to read_csv().

Related