You need to put double quotes around elements that contain commas.
The CSV format implements RFC 4180, which states:
- Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes.
So for instance (run code here.):
import StringIO
import csv
# the text between double quotes will be treated
# as a single element and not parsed by commas
line = '1,2,3,"1,2,3",4'
csv_file = StringIO.StringIO(line)
csv_reader = csv.reader(csv_file)
for data in csv_reader:
# output: ['1', '2', '3', '1,2,3', '4']
print data
As another option, you can change the delimiter. The default for csv.reader is delimiter=',' and quotechar='"' but both of these can be changed depending on your needs.
Semicolon Delimiter:
line = '1;2;3;1,2,3;4'
csv_file = StringIO.StringIO(line)
csv_reader = csv.reader(csv_file, delimiter=';')
for data in csv_reader:
# output: ['1', '2', '3', '1,2,3', '4']
print data
Vertical Bar Quotechar
line = '1,2,3,|1,2,3|,4'
csv_file = StringIO.StringIO(line)
csv_reader = csv.reader(csv_file, quotechar='|')
for data in csv_reader:
# output: ['1', '2', '3', '1,2,3', '4']
print data
Also, the python csv module works on python 2.6 - 3.x, so that shouldn't be the problem.