-1

I am reading a column of csv file using reader method. One of my column contains string value with comma in it. But reader is reading it as a two different value when I use delimiter as comma.

My requirement is, code should read this column value as a single string only and reader method should use delimiter as a comma only.

Input : "11"11","Bob Marley, USA","ABC"

Code :

reader = csv.reader(csv_file, delimiter=',', quotechar="'")
output = []
for row in reader:
    output = list(row)
    for each in output:
        print(each) 

Output:

"11"11"
"Bob Marley
 USA"
"ABC"

Desired output: "1111" "Bob Marley USA" "ABC"

Rohit
  • 27
  • 1
  • 8

1 Answers1

1

Your quotechar="'" should be quotechar='"', since the input uses " for String values.

Edit 1:

You cannot use control characters inside the cells without escaping them, so your input needs to escape each " inside a cell. Otherwise it will break.

The following code will work for "11\"11","Bob Marley, USA","ABC", but not "11"11","Bob Marley, USA","ABC":

reader = csv.reader(csv_file, delimiter=',', escapechar='\\', quotechar='"')
for row in reader:
    for cell in row:
        print cell

You might be able to replace the " with \" with a regular expression.

Dennis Griesert
  • 161
  • 1
  • 2
  • 7
  • Ok. But if we get the double quote also in string value then it's not gonna work anymore. This is a bug in csv file and I have to write a code to deal with it. – Rohit Dec 10 '18 at 12:47
  • In that case, you need to escape those quotemarks with a backslash and add `escapechar='\\'` to the reader's options. See [here](https://stackoverflow.com/a/21527375/10761013) – Dennis Griesert Dec 10 '18 at 12:53
  • I updated my answer. The CSV reader will not be able to handle your current input the way you desire. You have to clean the input in another way beforehand. – Dennis Griesert Dec 10 '18 at 13:21