# Read every other line into a variable from a text file

**URL:** <https://discourse.julialang.org/t/read-every-other-line-into-a-variable-from-a-text-file/78052>\
**Category:** General Usage\
**Tags:** loops\
**Created:** [March 17, 2022, 9:45pm UTC](https://discourse.julialang.org/t/read-every-other-line-into-a-variable-from-a-text-file/78052 "2022-03-17T21:45:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jdbeck66](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jdbeck66/32/19399_2.png) [@Jdbeck66](https://discourse.julialang.org/u/Jdbeck66)\
**Post date:** [March 17, 2022, 9:45pm UTC](https://discourse.julialang.org/t/read-every-other-line-into-a-variable-from-a-text-file/78052/1 "2022-03-17T21:45:38Z")

</div>

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

```julia
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

---

<div class="post-metadata">

**Author:** ![fredrikekre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fredrikekre/32/1688_2.png) [@fredrikekre](https://discourse.julialang.org/u/fredrikekre)\
**Post date:** [March 17, 2022, 9:54pm UTC](https://discourse.julialang.org/t/read-every-other-line-into-a-variable-from-a-text-file/78052/2 "2022-03-17T21:54:33Z")

</div>

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

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

```

---

<div class="post-metadata">

**Author:** ![Jdbeck66](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jdbeck66/32/19399_2.png) [@Jdbeck66](https://discourse.julialang.org/u/Jdbeck66)\
**Post date:** [March 17, 2022, 9:57pm UTC](https://discourse.julialang.org/t/read-every-other-line-into-a-variable-from-a-text-file/78052/3 "2022-03-17T21:57:53Z")

</div>

That’s awesome.

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

Thanks.
