Python CSV read from string hack

I’ve wanted to use the python CSV package to read from a string a couple of times now, and I always forget this cheesey little hack so I’m writing it down in the hopes I will be able to find it in the future.

There are a couple of other approaches out there for doing this, but for reading a single line CSV string this is by far the simplest and shortest, perhaps too terse. The more general version of this is to use the following csv.reader( x.split( os.linesep ) ) for multiline csv strings.

x = '1,2,3,"stuff",5'
import csv
csv_reader = csv.reader( [ x ] )
for row in csv_reader
print row
x = '1,2,3,"stuff",5' import csv csv_reader = csv.reader( [ x ] ) for row in csv_reader: print row
['1', '2', '3', 'stuff', '5']

4 Comments

  1. andre says:

    very nice, helped me with the “_csv.Error: new-line character seen in unquoted field – do you need to open the file in universal-newline mode?” issue

  2. Sachin Rekhi says:

    Exactly what I was looking for! Thanks buddy.

  3. Mark says:

    Nice one! Its always the little niggly things that have me searching around stumped with Python – thank you this is exactly what I wanted!

  4. Also check out StringIO:

    for row in csv.reader(StringIO.StringIO(x)): print row

Leave a Reply