What is the equivalent of python's with open(file) in julia

Viewed 109

Is there an equivalent to python's with open() idiom in Julia?

>>> with open(path, "r") as file:
...    file.readlines()
['beep\n', 'boop\n']
1 Answers

I don't know what the most idiomatic way is, but you have several options:

julia> readlines("tmp.log")
2-element Array{String,1}:
 "beep"
 "boop"
julia> read(file, String)
"beep\nboop\n"
julia> open("tmp.log", "r") do file
           while !eof(file)
               @show readline(file)
           end
       end
readline(file) = "beep"
readline(file) = "boop"
julia> for line in eachline("tmp.log")
           @show line
       end
line = "beep"
line = "boop"

See the docs for more.

Related