How to skip the first line of a CSV file and make the second line the header

前端 未结 5 614
有刺的猬
有刺的猬 2020-12-07 02:37

Is there a way to skip the first line of a CSV file and make the second line act as the header?

I have a CSV file that has the date on the first row and the headers

5条回答
  •  無奈伤痛
    2020-12-07 03:34

    I don't think there's an elegant way of doing it, but it can be done:

    require "csv"
    
    # Create a stream using the original file.
    # Don't use `textmode` since it generates a problem when using this approach.
    file = File.open "file.csv"
    
    # Consume the first CSV row.
    # `\r` is my row separator character. Verify your file to see if it's the same one.
    loop { break if file.readchar == "\r" }
    
    # Create your CSV object using the remainder of the stream.
    csv = CSV.new file, headers: true
    

提交回复
热议问题