Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

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

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 on the second row, so I need to be able to skip the first row when iterating over it. I tried using slice but that converts the CSV to an array and I really want to read it as CSV so I can take advantage of headers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">
#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">
#<CSV::Row "a":"1" "b":"2" "c":"3" "d":"4">

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

require 'csv'

CSV.parse(DATA.read,:col_sep=>';',:headers=>true,
    :skip_lines=> /^dddd-dd-dd$/  #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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...