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 csvcsv_reader = csv.reader( [ x ] )for row in csv_readerprint rowx = '1,2,3,"stuff",5' import csv csv_reader = csv.reader( [ x ] ) for row in csv_reader: print row
['1', '2', '3', 'stuff', '5']
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
Exactly what I was looking for! Thanks buddy.
Nice one! Its always the little niggly things that have me searching around stumped with Python – thank you this is exactly what I wanted!
Also check out StringIO:
for row in csv.reader(StringIO.StringIO(x)): print row