TypeError:"quotechar"必须为1个字符的字符串 [英] TypeError: "quotechar" must be an 1-character string
问题描述
我正在尝试从csv文件读取数据.我将quotechar设置为csv.QUOTE_NONE.
I am trying to read data from a csv file. I set quotechar to csv.QUOTE_NONE.
我为此目的编写的四行Python如下-
The four lines of Python I wrote for this purpose are just as follows -
import csv
with open('mtz.gps.comfort_gps_logs_20110214_20110215.csv', 'rb') as csvfile:
taxiDataReader = csv.reader(csvfile, delimiter = ',', quotechar = csv.QUOTE_NONE)
for row in taxiDataReader:
print row
但是,当我运行这些命令时,我收到此错误消息-
However, when I run these, I get this error message -
Traceback (most recent call last):
File "log.py", line 3, in <module>
taxiDataReader = csv.reader(csvfile, delimiter = ',', quotechar = csv.QUOTE_NONE)
TypeError: "quotechar" must be an 1-character string
我不仅想了解为什么会出现此特定错误,还希望更详细地了解quotechar的真正作用.
I would not only like to understand why this particular error shows up but also understand in more detail what the role of quotechar really is.
推荐答案
QUOTE_NONE
是作为参数quoting
的值,而不是quotechar
的值.
QUOTE_NONE
is meant as a value for the parameter quoting
, not for quotechar
.
正确的方法是使用
taxiDataReader = csv.reader(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
文档说明
The docs state that quotechar
must always be a one-character string, its role is simply to choose which character should be used for quoting.
在许多情况下报价都是必需的,例如
Quoting becomes necessary in a variety of situations, for example
- 如果CSV字段包含分隔符(例如逗号)
- 如果CSV字段包含换行符.
在这两种情况下,CSV阅读器都需要知道这些字符是文字字符,而不是控制字符.因此,如果您想将值[1, "hello", "1,2,3", "hi\nthere"]
放入CSV文件,则结果为
In both these cases the CSV reader needs to know that these characters are meant as literal characters, not as control characters. So, if you wanted to put the values [1, "hello", "1,2,3", "hi\nthere"]
into a CSV file, it would be quite bad if the result was
1,hello,1,2,3,hi
there
不是吗?因此,这些字段用引号引起来:
wouldn't it? Therefore, these fields are quoted:
1,hello,"1,2,3","hi\nthere"
quoting
控制何时引用(默认为QUOTE_MINIMAL
,即仅在绝对需要引用时).如果您完全关闭引号(QUOTE_NONE
),则quotechar
的值当然毫无意义.
quoting
controls what will be quoted when (defaulting to QUOTE_MINIMAL
, i.e., only when quotes are absolutely necessary). If you turn off quoting entirely (QUOTE_NONE
), the value of quotechar
is of course meaningless.
这篇关于TypeError:"quotechar"必须为1个字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!