Eachline function and more than one line

Hello,
Can I use the eachline function to read multiple lines?

Thank you.

Yes. eachline actually iterates over all lines in the file. So either do:

for line in eachline(file)
    # do something to the line
end

Or use collect to gather all lines:

collect(eachline(file)) # gives Vector{String} containing all lines
1 Like

Or just use readlines :slight_smile:

2 Likes

What the other replies have given are the most common ways to use eachline. If for some reason you actually have a use case where you need to read the file a specific number of multiple lines (eg. 3 lines) at a time, you can apply first to the iterator that eachline returns, and give it the number of lines to read. For eg.:

let e = eachline("./myfile.txt"; keep=true)
  while true
    # read (upto) 3 lines from the file
    lns = first(e, 3)
    # if we've already read the whole file, exit
    isempty(lns) && break

    #do something with the lines we read
    println(join(lns))
  end
end
3 Likes

Hello,
Thank you so much.