为什么这段代码引发csv.Error? [英] Why does this code raise csv.Error?
问题描述
我想使用Python的内建 csv 写出CSV模块。
I'm trying to write out CSV using Python's built-in csv module.
import csv
import sys
writer = csv.writer(sys.stdout, delimiter="|", quoting=csv.QUOTE_NONE)
writer.writerow(['"foo', "bar"])
我期望的输出是:
"foo|bar
但是,我得到:
Error: need to escape, but no escapechar set
文档说:
当当前分隔符出现在输出数据中时,它的前面是当前escapechar字符。如果未设置escapechar,则在遇到需要转义的任何字符时,写入程序将引发错误。
When the current delimiter occurs in output data it is preceded by the current escapechar character. If escapechar is not set, the writer will raise Error if any characters that require escaping are encountered.
现在, ',管道字符)不会出现在数据的任何位置。为什么CSV写入器尝试转义某物?
Now, the delimiter ('|', the pipe character) doesn't appear anywhere in the data. Why is the CSV writer trying to escape something?
推荐答案
设置 quoting = csv.QUOTE_NONE
是不够的;您还需要将 quotechar
设置为空字符串:
Setting quoting=csv.QUOTE_NONE
is not enough; you also need to set quotechar
to an empty string:
>>> import sys
>>> import csv
>>> writer = csv.writer(sys.stdout, delimiter="|", quoting=csv.QUOTE_NONE, quotechar='')
>>> writer.writerow(['"foo', "bar"])
"foo|bar
否则, csv.writer()
将尝试转义任何现有的 quotechar
字符,但它需要 csv.escapechar
。
Otherwise, csv.writer()
will try to escape any existing quotechar
characters, but it needs csv.escapechar
to be set for that.
这篇关于为什么这段代码引发csv.Error?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!