我有一个大型CSV文件。我想从第n行开始阅读。目前我有以下代码
CSV.foreach(path) do |row|
#process
end
我需要从文件n开始阅读。
答案 0 :(得分:2)
您可以使用.readlines方法读取特定行:
require 'csv'
p CSV.readlines(path)[15..20] # array returned
# Benchmark
# user system total real
# 0.020000 0.000000 0.020000 ( 0.015769)
其他方式(我认为,不应该将整个文件加载到内存中):
from = 15
to = 20
csv = CSV.open(file, 'r')
# skipping rows before one we need
from.times { csv.readline }
# reading rows we need
(to - from).times { p csv.readline }
# Benchmark
# user system total real
# 0.000000 0.000000 0.000000 ( 0.000737)