我正在尝试使用 Python 的内置 csv 写出 CSV模块。
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
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 编写器试图转义某些内容?
最佳答案
设置 quoting=csv.QUOTE_NONE
是不够的;您还需要将 quotechar
设置为空字符串:
>>> 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
那个。
关于python - 为什么此代码会引发 csv.Error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296356/