Read every other line into a variable from a text file

I’d like to read every other (or every third, fourth,…) line from a text file into a variable.

function readtext(file)
    lines = String[]
    for line ∈ eachline(file)
        push!(lines, line::String) 
    end
    return lines    
end

I’ve been doing this but thought I should be able to do some list comprehension after I open the file, maybe. Seems like there should be a much more elegant solution.

Any suggestions,

JB

Every second line (starting with line no. 1):

lines = [line for (i, line) in enumerate(eachline(file)) if i % 2 == 1]
1 Like

That’s awesome.

Didn’t consider enumerating (eachline(file)). I guess that each line(file) is an interator so that makes sense.

Thanks.