Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a single CSV string?

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.

like image 739
Ahmad Avatar asked Mar 06 '16 03:03

Ahmad


2 Answers

Take a closer look at the documentation for the csv module, which says:

reader(...)
    csv_reader = reader(iterable [, dialect='excel']
                            [optional keyword args])
        for row in csv_reader:
            process(row)

    The "iterable" argument can be any object that returns a line
    of input for each iteration, such as a file object or a list.  The
    optional "dialect" parameter is discussed below.  The function
    also accepts optional keyword arguments which override settings
    provided by the dialect.

So if you have string:

>>> s = '"this is", "a test", "of the csv", "parser"'

And you want "an object that returns a line of input for each iteration", you can just wrap your string in a list:

>>> r = csv.reader([s])
>>> list(r)
[['this is', 'a test', 'of the csv parser']]

And that's how you parse a string with the csv module.

like image 150
larsks Avatar answered Sep 19 '22 12:09

larsks


You can still parse a single string with csv. Use StringIO to write a string buffer (also known as memory files):

import csv
from StringIO import StringIO

s = "your string"
buff = StringIO(s)

reader = csv.reader(buff)
for line in reader:
    print(line)
like image 41
alecxe Avatar answered Sep 19 '22 12:09

alecxe