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  ['1', '2', '3', 'stuff', '5']

One Comment

  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

Leave a Reply