When reading a csv file with ruby, is it possible to read only the first two lines including the header and not the others?

The number of lines in the csv file is large, and if it is.reador.foreach, it takes time to process because all lines are read.

Specifically, the following CSV data has about 20000 rows,
Since we want to output only "1,20180821,100,35" on the second line, there is no need to read the third and subsequent lines.

No, Time, kakaku, kosuu


When I looked into it, I felt that it was quite so much if I used.map, but I didn't understand.
It would be helpful if you could give me sample code.

Thank you.

(It is not possible to create a separate file for the first and second lines and read it.)

  • Answer # 1

    require "csv"
    CSV.open ("file.csv") do | csvfile |
        title = csvfile.gets
        data = csvfile.gets
        p title
        p data

    I want to output only "1,20180821,100,35" on the second line

    If you want to output as a string instead of CSV data,

    open ("file.csv") do | file |
        title = file.gets
        data = file.gets
        puts title
        puts data

  • Answer # 2

    The CSV library can parse a single line of text as CSV using CSV.parse_line.


    Also, if you pass Array corresponding to the header line of CSV with: headers, you can use it like Hash with header as key.

    If the sample CSV is named foo.csv, it will be as follows.

    require 'csv'
    csv_filename = "foo.csv"
    File.open (csv_filename) do | f |
      line1 = f.gets
      line2 = f.gets
      header = CSV.parse_line (line1)
      csv_body = CSV.parse_line (line2, headers: header)
      p csv_body ["kosuu"] # =>35

  • Answer # 3

    require 'csv'
    row2 = nil
    row = CSV.foreach ('data.csv', headers: true) do | row |
      row2 = row
    p row2

    Execution example