如何跳过CSV文件的第一行并将第二行作为标题

有没有办法跳过CSV文件的第一行并使第二行充当标题?

我有一个CSV文件,第一行有日期,第二行有标题,所以我需要能够在迭代时跳过第一行。 我尝试使用slice但将CSV转换为数组,我真的想将其读作CSV,以便我可以利用标头。

我不认为有一种优雅的方式,但它可以做到:

 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 

根据您的数据,您可以使用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 

结果是

 # # # 

在您的情况下,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 

或者您可以使用更多延伸起始线:

 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 

我有同样的问题(除了我想在开头跳过超过1行)并且在寻找一个好的解决方案时遇到了这个问题。 对于我的情况,我使用了这个答案中描述的代码来解决类似的问题 ,除了我正在使用你提到的标题选项。

 CSV.parse(File.readlines(path).drop(1).join, headers: true) do |row| # ... now I can use: row['column_name'] end 

你可以这样做

 text = File.readlines("file.csv")[1..-1].join() csv = CSV.parse(text, headers: true) 

这个简单的代码对我有用。 您可以读取CSV文件并忽略其第一行,即标题或字段名称:

 CSV.foreach(File.join(File.dirname(__FILE__), filepath), headers: true) do |row| puts row.inspect end 

你可以用row做你想做的事。 不要忘记使用headers: true