简体   繁体   中英

how to read first 5 lines of csv file using built in ruby csv

My application lets user to upload csv file with maximum of 50MB. I wanted to show the user the preview of the uploaded file. Can I read only the first 5 lines of csv? I am currently using CSV.read function, obviously this will read the entire file and is slow.

CSV#foreach返回一个可枚举的,因此只需对其调用Enumerable#take

csv_preview_data = CSV.foreach(csv_path, headers: false).take(5)

我认为读取固定数量记录的最简单方法是:

preview_data = CSV.readlines(csv_path, headers: false)[0,5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM