简体   繁体   English

csv writer在python中添加了两次双引号

[英]csv writer adds double quotes twice in python

I have written a python script to append href attribute and tag to a string holding a url which is in a csv file.我编写了一个 python 脚本来将 href 属性和标签附加到一个字符串,该字符串包含一个 csv 文件中的 url。 The problem is that the result is not as expected.问题是结果不如预期。 The resulted html string has got an extra double quote instead of single.结果 html 字符串有一个额外的双引号而不是单引号。 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>"

This is correct behaviour.这是正确的行为。 Double quotes are escaped inside csv value.双引号在 csv 值内转义。

If you want to output without escaping try csv.QUOTE_NONE如果您想在不转义的情况下输出,请尝试csv.QUOTE_NONE

csv.writer(OutputFile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONE)

I ran into this when trying to store a JSON object as a string in a column in a csv.我在尝试将 JSON 对象作为字符串存储在 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)

For those who are having a "Error: need to escape" error:对于那些遇到"Error: need to escape"错误的人:

Try this:试试这个:

writer = csv.writer(f, quoting=csv.QUOTE_NONE, delimiter='|', quotechar='',escapechar='\\')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM