Read CSV file with comma within fields in Python

前端 未结 1 676
长情又很酷
长情又很酷 2020-11-27 21:09

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,         


        
相关标签:
1条回答
  • 2020-11-27 21:20

    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']]
    
    0 讨论(0)
提交回复
热议问题