如何在Ruby中读取CSV时跳过标题行?
问题描述:
Ruby的CSV
类使它很容易的每一行遍历:如何在Ruby中读取CSV时跳过标题行?
CSV.foreach(file) { |row| puts row }
然而,这始终包括标题行,所以我会得到作为输出:
header1, header2
foo, bar
baz, yak
我不虽然想要标题。现在,当我打电话......
CSV.foreach(file, :headers => true)
我得到这样的结果:
#<CSV::Row:0x10112e510
@header_row = false,
attr_reader :row = [
[0] [
[0] "header1",
[1] "foo"
],
[1] [
[0] "header2",
[1] "bar"
]
]
>
当然,因为文件说:
此设置导致#shift返回行为CSV: :行对象而不是阵列
但是,怎么可以我跳过标题行,将行作为简单数组返回?我不想复杂的CSV::Row
对象被返回。
我绝对不希望这样做:
first = true
CSV.foreach(file) do |row|
if first
puts row
first = false
else
# code for other rows
end
end
答
看#shift从CSV类:用于包装的弦乐和IO
主要读法,单行从拉数据源,解析并返回字段的阵列(如果不使用标题行)
为例:
require 'csv'
# CSV FILE
# name, surname, location
# Mark, Needham, Sydney
# David, Smith, London
def parse_csv_file_for_names(path_to_csv)
names = []
csv_contents = CSV.read(path_to_csv)
csv_contents.shift
csv_contents.each do |row|
names << row[0]
end
return names
end
答
一个很酷的方式忽略头被读取它作为一个数组,而忽略第一行:
data = CSV.read("dataset.csv")[1 .. -1]
# => [["first_row", "with data"],
["second_row", "and more data"],
...
["last_row", "finally"]]
的:headers => false
方法的问题在于CSV
不会尝试读取第一行作为标题,但会将其视为数据的一部分。所以,基本上,你有一个无用的第一行。
检查http://*.com/a/37856698/473040 – equivalent8 2016-06-16 10:35:29