TypeError: “quotechar” must be an 1-character string

后端 未结 1 1609
生来不讨喜
生来不讨喜 2021-01-19 08:12

I am trying to read data from a csv file. I set quotechar to csv.QUOTE_NONE.

The four lines of Python I wrote for this purpose are just as follows -

         


        
1条回答
  •  醉梦人生
    2021-01-19 08:14

    QUOTE_NONE is meant as a value for the parameter quoting, not for quotechar.

    The correct way would be to use

    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

    • if a CSV field contains the separator character (e. g. a comma)
    • if a CSV field contains a linefeed characters.

    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 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.

    0 讨论(0)
提交回复
热议问题