有没有办法跳过CSV文件的第一行并使第二行充当标题?
我有一个CSV文件,该文件的第一行具有日期,第二行具有标题,因此我需要能够在对其进行迭代时跳过第一行。我尝试使用,slice但是将CSV转换为数组,我真的很想将其读取为CSV,以便可以利用标头。
根据您的数据,可以在skip_lines-option中使用另一种方法
该示例跳过所有行 #
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
Run Code Online (Sandbox Code Playgroud)
结果是
#<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">
Run Code Online (Sandbox Code Playgroud)
对于您的情况,csv包含一个日期,因此您可以使用:
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
Run Code Online (Sandbox Code Playgroud)
或者您可以使用更多延长起跑线:
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
Run Code Online (Sandbox Code Playgroud)
我认为没有一种优雅的方法,但可以做到:
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
Run Code Online (Sandbox Code Playgroud)