3

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.

1

2 Answers 2

17

CSV#foreach returns an enumerable, so just call Enumerable#take on it:

csv_preview_data = CSV.foreach(csv_path, headers: false).take(5)
Sign up to request clarification or add additional context in comments.

2 Comments

Does it reads only first 5 lines without loading all file in the memory?
@Зелёный foreach.lazy.take(5).force probably does is lazily.
1

The simplest ways to read a fixed number of records for my opinion would be:

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

1 Comment

This will load the entire CSV into memory, avoid this method for big files

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.