CSV.open
会在 block 退出时将数据存储在内存中并写入文件一次,还是自动分批写入?
require 'csv'
CSV.open('result.csv', 'wb') do |csv|
while row = next_row
csv << row
end
end
最佳答案
CSV.open
将在 block 关闭时写入底层操作系统,并且每次缓冲区填充和刷新时也会写入,这将自动发生。 (在我的 Ruby 安装中,它发生在 8196 字节处。)您还可以将 csv.flush
添加到您的 block 中以强制它按顺序写入。
require 'csv'
CSV.open('result.csv', 'wb') do |csv|
while row = next_row
csv << row # Without flush, writes to underlying OS only when buffer fills
csv.flush # Adding this forces a write to underlying OS
end
end # Exiting block writes to underlying OS and closes file handle
(请注意,写入是针对底层操作系统,它可能会在实际写入磁盘之前再次缓冲流。)
关于ruby - Ruby 的 CSV.open 是否缓冲到内存并一次写入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168814/