Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csv writer adds double quotes twice in python

Tags:

python

html

csv

I have written a python script to append href attribute and tag to a string holding a url which is in a csv file. The problem is that the result is not as expected. The resulted html string has got an extra double quote instead of single. Any suggestion how to fix this? Below is the snippet:

InputFile = open('data1.csv', 'rb')
OutputFile = open('data3.csv', 'a+b')

CsvReader_InputFile = csv.reader(InputFile, delimiter=',', quotechar='\"')
CsvWriter_OutputFile = csv.writer(OutputFile, delimiter=',', quotechar='\"')

Row_InputFile = CsvReader_InputFile.next()
Row_InputFile[2] = "<a href=\"" + Row_InputFile[2] + "\">Link</a>"
CsvWriter_OutputFile.writerow(Row_InputFile)

Output:

"<a href=""http://www.google.com"">Link</a>"

Wanted Output:

"<a href="http://www.google.com">Link</a>"
like image 689
ibrahimdanish Avatar asked Sep 18 '15 13:09

ibrahimdanish


People also ask

Why does my CSV have double quotes?

Since CSV files use the comma character "," to separate columns, values that contain commas must be handled as a special case. These fields are wrapped within double quotation marks. The first double quote signifies the beginning of the column data, and the last double quote marks the end.

How do I fix a double quote in a CSV file?

There are 2 accepted ways of escaping double-quotes in a CSV file. One is using a 2 consecutive double-quotes to denote 1 literal double-quote in the data. The alternative is using a backslash and a single double-quote.

How do you get rid of double quotes in Python?

Using the strip() Function to Remove Double Quotes from String in Python. We use the strip() function in Python to delete characters from the start or end of the string. We can use this method to remove the quotes if they exist at the start or end of the string.

What is a Quotechar in CSV Python?

quotechar specifies the character used to surround fields that contain the delimiter character. The default is a double quote ( ' " ' ). escapechar specifies the character used to escape the delimiter character, in case quotes aren't used.


2 Answers

This is correct behaviour. Double quotes are escaped inside csv value.

If you want to output without escaping try csv.QUOTE_NONE

csv.writer(OutputFile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONE)
like image 190
Andriy Kuba Avatar answered Oct 02 '22 02:10

Andriy Kuba


I ran into this when trying to store a JSON object as a string in a column in a csv. I had single quotes around a string filled with double quotes. my row of data looked like

['foo', 'bar', '{"foo":"bar". "bar":"foo"}']

Doing this solved it for me

writer = csv.writer(csv_file, delimiter=',', quotechar="\'", quoting=csv.QUOTE_NONE)
like image 44
aaron Avatar answered Oct 02 '22 00:10

aaron