Julia Reading Files
Line reading is a way to load a file as separate lines of text. Each line becomes one string in an array.
readlines gives each line as a string
The block writes a file with two lines in the same block. The read result shows both lines.
write("notes.txt", "First line\nSecond line")
println(readlines("notes.txt"))The open do form reads a file
The block first writes the file in the same block. The open form then reads and prints its text.
write("notes.txt", "First line\nSecond line")
open("notes.txt") do f
println(read(f, String))
endlength counts the lines
The file written here has three lines. The count printed is 3.
write("notes.txt", "One\nTwo\nThree")
println(length(readlines("notes.txt")))Example
write("notes.txt", "First line\nSecond line")
lines = readlines("notes.txt")
println(lines[1])
println(lines[2])
println(length(lines))Key points
- readlines: a function that gives the lines of a file as an array of strings.
- Newline mark: the two characters backslash and n inside text start a new line in the file.
- Line count: length on the readlines result counts the lines in the file.
- open do form: a block form that opens a file and closes it when the block ends.
- read in a block: read(f, String) inside the block gives the whole text from the open file.
In this example, the block first writes a two-line file in the same block. readlines loads the lines into an array, so the first two prints show one line each. The last print shows the line count of 2.
Note
readlines gives plain strings, so printing its result shows the lines in square brackets.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A file holds the text One, a newline, and then Two. What does length(readlines on that file) give?