从Ruby中的csv文件中获取第二行 [英] Fetching second row from csv file in Ruby
问题描述
actual_row = File.open(file_name[0], 'r')
first_row_data = []
CSV.foreach(actual_row) do |row|
first_row_data << row[1]
end
puts first_row_data
为此,我试图获取CSV的第二行,但它正在打印第二列.
With this I am trying to fetch the second row of CSV but it is printing the second column instead.
推荐答案
如果未给出任何块,则foreach
方法将返回一个枚举数,这使您可以使用
The foreach
method returns an enumerator if no block is given, which allows you to use methods such as drop
from Enumerable
:
# outputs all rows after the first
CSV.foreach('test.csv').drop(1).each { |row| puts row.inspect }
要只限于一行,我们可以 take
:
To limit to just one row, we can then take
:
# outputs only the second row
CSV.foreach('test.csv').drop(1).take(1).each { |row| puts row.inspect }
但是,我们仍在解析整个文件,只是丢弃了大部分文件.幸运的是,我们可以在混合中添加 lazy
:
But, we're still parsing the entire file and just discarding most of it. Luckily, we can add lazy
into the mix:
# outputs only the second row, parsing only the first 2 rows of the file
CSV.foreach('test.csv').lazy.drop(1).take(1).each { |row| puts row.inspect }
但是,如果第一行是标题行,请不要忘记您可以将它告诉CSV:
But, if the first row is a header row, don't forgot you can tell CSV about it:
# outputs only the second row, as a CSV::Row, only parses 2 rows
CSV.foreach('test.csv', headers: true).take(1).each { |row| puts row.inspect }
顺便说一句(如果我做错了),看起来shift
方法是CSV用于解析行的方法,所以我刚刚添加了:
As an aside (in case I did this wrong), it looks like the shift
method is what CSV is using for parsing the rows, so I just added:
class CSV
alias :orig_shift :shift
def shift
$stdout.puts "shifting row"
orig_shift
end
end
并运行了一个示例csv,以查看每个示例输出了多少次平移行".
and ran with a sample csv to see how many times "shifting row" was output for each of the examples.
这篇关于从Ruby中的csv文件中获取第二行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!