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

前端 未结 5 624
有刺的猬
有刺的猬 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:24

    Depending on your data you may use another approach with theskip_lines-option

    This examples skip all lines with a leading #

    require 'csv'
    
    CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
        :skip_lines=> /^#/  #Mark comments!
      ) do |row|
      p row
    end
    #~ 
    __END__
    #~ Comment
    #~ More comment
    a;b;c;d
    1;2;3;4
    #~ More comment
    1;2;3;4
    #~ More comment
    1;2;3;4
    

    The result is

    #
    #
    #
    

    In your case the csv contains a date, so you may use:

    require 'csv'
    
    CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
        :skip_lines=> /^\d\d\d\d-\d\d-\d\d$/  #Skip line with date only
      ) do |row|
      p row
    end
    #~ 
    __END__
    2016-03-19
    a;b;c;d
    1;2;3;4
    1;2;3;4
    1;2;3;4
    

    or you could use more extend starting lines:

    require 'csv'
    
    CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
        :skip_lines=> /^Created by/  #Skip line with date only
      ) do |row|
      p row
    end
    
    __END__
    Created by test.rb on 2016-03-19
    a;b;c;d
    1;2;3;4
    1;2;3;4
    1;2;3;4
    

提交回复
热议问题