rodling rodling - 1 year ago 88
Python Question

CSV breaks up values on non delimeter

I am trying to read mixed CSV fields, where there are quoted fields and non-quoted numerical with the following :

from csv import reader

bar = """1234,"abc,def","dasd",341234234"""
foo = reader(bar)
[x for x in foo]

this returns

[['1'], ['2'], ['3'], ['4'], ['', ''], ['abc,def'], ['', ''], ['dasd'], ['', ''], ['3'], ['4'], ['1'], ['2'], ['3'], ['4'], ['2'], ['3'], ['4']]

I tried using
foo = reader(bar, delimiter=',', quotechar='"')

But it still breaks up numbers. I basically need to read csv.QUOTE_NONNUMERIC
from writer, but it is not reading it properly.

Answer Source

csv reader works on file objects. Here is what you could do

from csv import reader
import StringIO

bar = """1234,"abc,def","dasd",341234234"""
f = StringIO.StringIO(bar)
foo = reader(f,  delimiter=',')
print [x for x in foo]

This will give you o/p

[['1234', 'abc,def', 'dasd', '341234234']]

Hope that works for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download