32

I need to read a CSV file which has fields that have a comma, so I have double quoted the fields which contains commas, such as:

1, "text1,text2", "text3, text4", a, b, c

But when I try to read the file in Python I get the fields separated by the commas, as following:

row[0] = 1
row[1] = text1
row[2] = text2
row[3] = text3
row[4] = text4
row[5] = a
row[6] = b
row[7] = c

I am reading the CSV file with the following code:

info = csv.reader(open('./info.csv'))  
for row in info :
    print row[0] + " * " + row[1] ...

Is it possible to read double quoted fields which contains a comma?

Mel
  • 5,837
  • 10
  • 37
  • 42
David
  • 595
  • 1
  • 8
  • 19

2 Answers2

44

The Python csv module actually does support quoted fields, even by default. Your problem here is that Python by default does not skip the space, so you need to use skipinitialspace=True.

>>> s = StringIO.StringIO('1, "text1,text2", "text3, text4", a, b, c')
>>> list(csv.reader(s, skipinitialspace=True))
[['1', 'text1,text2', 'text3, text4', 'a', 'b', 'c']]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 5
    `csv.Sniffer().sniff(s).__dict__` would indicate it too: `{'__doc__': None, '__module__': 'csv', '_name': 'sniffed', 'delimiter': ',', 'doublequote': False, 'lineterminator': '\r\n', 'quotechar': '"', 'quoting': 0, 'skipinitialspace': True}` – eumiro Nov 29 '11 at 14:05
  • idk how but you should be paid for this answer.. :D thanks Sven Marnach this just solved my problem.. God bless you – Assad Ali Mar 07 '22 at 13:51
  • 1
    @AssadAli Thanks for the kind words. I'm glad this answer helps. – Sven Marnach Mar 07 '22 at 21:42
1

You need to use a DictReader on the file content.

The result looks like this

import csv

with open(file_name, mode ='r', encoding='utf-8') as file:
  # reading the CSV file
  csvFile = csv.DictReader(file)
  # displaying the contents of the CSV file
  for line in csvFile:
    print(line["myAttribute"]
Ryan M
  • 18,333
  • 31
  • 67
  • 74