eachline
eachline(stream)
Create an iterable object that will yield each line from a stream.
Examples
Iterate over a file's contents
julia> fp = open("numbers.txt");
julia> iter = eachline(fp);
julia> for i in iter
print(i)
end
1
2
3
4
5
julia> close(fp)
julia> io = IOBuffer("Hello\nWorld\nJulia\n");
julia> lines = eachline(io);
julia> collect(lines)
3-element Array{String,1}:
"Hello"
"World"
"Julia"
In the example above, we create an IOBuffer io
containing several lines of text. We then use the eachline
function to generate an iterable object lines
that will yield each line from the stream. Finally, we collect all the lines using collect
to obtain an array of strings representing each line from the stream.
It's important to note that eachline
works with any type of stream, not just IOBuffer. You can use it with files, network streams, or any other stream-like object.
Here's an example with a file:
julia> file = open("data.txt", "r");
julia> lines = eachline(file);
julia> for line in lines
println(line)
end
In this example, we open a file named "data.txt" in read mode using the open
function. We then create an iterable object lines
using eachline
to iterate over each line in the file. Finally, we loop over each line using a for
loop and print it out.
It's worth mentioning that eachline
does not include the trailing newline character in the yielded lines. If you need to include it, you can use the readline
function instead.
See Also
deserialize, eachline, eof, fd, flush, IOBuffer, ismarked, isopen, isreadonly, mark, nb_available, open, pipeline, position, read, read!, readavailable, readbytes, readbytes!, readline, redirect_stderr, redirect_stdin, reset, seek, seekend, seekstart, serialize, skip, skipchars, TextDisplay, unmark, write, writemime,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.