我正在读取一个大小为 10mb 且包含一些 ID 的文件。我将它们读入 ruby 列表。我担心将来可能会导致内存问题,因为文件中的 id 数量可能会增加。有没有一种批量读取大文件的有效方法?
谢谢
最佳答案
与 Lazy Enumerators和 each_slice ,您可以两全其美。中间切线不用担心,可以批量迭代多行。 batch_size
可以自由选择。
header_lines = 1
batch_size = 2000
File.open("big_file") do |file|
file.lazy.drop(header_lines).each_slice(batch_size) do |lines|
# do something with batch of lines
end
end
它可用于将巨大的 CSV 文件导入数据库:
require 'csv'
batch_size = 2000
File.open("big_data.csv") do |file|
headers = file.first
file.lazy.each_slice(batch_size) do |lines|
csv_rows = CSV.parse(lines.join, headers: headers)
# do something with 2000 csv rows, e.g. bulk insert them into a database
end
end
关于ruby-on-rails - Ruby - 批量读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2962134/