在Ruby中读取CSV时,如何跳过标题行? [英] How can I skip the header row when reading a CSV in Ruby?
问题描述
Ruby的 CSV
类可以很容易地遍历每一行:
Ruby's CSV
class makes it pretty easy to iterate over each row:
CSV.foreach(file) { |row| puts row }
但是,这总是包括标题行,所以我将输出: / p>
However, this always includes the header row, so I'll get as output:
header1, header2
foo, bar
baz, yak
我不想要标题。现在,当我调用...
I don't want the headers though. Now, when I call …
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 :: Row对象而不是数组形式返回行
This setting causes #shift to return rows as CSV::Row objects instead of Arrays
,如何跳过标题行,将该行作为一个简单的数组返回?我不想复杂的 CSV :: Row
对象
我绝对不想这样做:
first = true
CSV.foreach(file) do |row|
if first
puts row
first = false
else
# code for other rows
end
end
推荐答案
查看 #shift 类别:
包装的Strings和IO的主要读取方法,单个行从数据源中提取,解析并作为字段数组返回(如果不使用标题行) i>
The primary read method for wrapped Strings and IOs, a single row is pulled from the data source, parsed and returned as an Array of fields (if header rows are not used)
例如:
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
这篇关于在Ruby中读取CSV时,如何跳过标题行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!