Ruby unable to parse a CSV file: CSV::MalformedCSVError (Illegal quoting in line 1.)

后端 未结 9 2134
被撕碎了的回忆
被撕碎了的回忆 2021-02-03 22:17

Ubuntu 12.04 LTS

Ruby ruby 1.9.3dev (2011-09-23 revision 33323) [i686-linux]

Rails 3.2.9

Following is

相关标签:
9条回答
  • 2021-02-03 23:13

    from this thread pass the option :quote_char => "|"

    CSV.read(filename, :quote_char => "|")
    
    
    0 讨论(0)
  • 2021-02-03 23:15

    I had a problem with the trademark character that was throwing this error.

    The trademark character translates to \"! in UTF-8, so it was the open-ended quotation symbol that was throwing the error. So I did this:

    .gsub!("\"!", "")

    And then I tried creating my CSV object and it worked fine.

    0 讨论(0)
  • 2021-02-03 23:19
    quote_chars = %w(" | ~ ^ & *)
    begin
      @report = CSV.read(csv_file, headers: :first_row, quote_char: quote_chars.shift)
    rescue CSV::MalformedCSVError
      quote_chars.empty? ? raise : retry 
    end
    

    it's not perfect but it works most of the time.

    N.B. CSV.parse takes the same parameters as CSV.read, so either a file or data from memory can be used

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