Julia Files
A file is stored text that stays on the computer after a program ends. A program can write text to a file and read that text back.
write creates a file
The write call stores the text in notes.txt. The existence check then prints true.
write("notes.txt", "First line")
println(isfile("notes.txt"))read gives the whole stored text
The block first writes the file in the same block. It then reads the text back.
write("notes.txt", "First line")
println(read("notes.txt", String))A second write replaces the first
The file is written twice in this block. Only the second text is read back.
write("notes.txt", "Old text")
write("notes.txt", "New text")
println(read("notes.txt", String))Example
write("notes.txt", "Shopping list")
println(isfile("notes.txt"))
println(read("notes.txt", String))Key points
- write: a function that writes text to a file at a stated path.
- Replace: write creates the file when it is missing and replaces old content when it exists.
- read: a call with String that gives the whole text of a file.
- isfile: a function that tells whether a file exists at a path.
- Path: the file name in these lessons is the path because the file sits in the working folder.
In this example, write stores the text Shopping list in notes.txt. The isfile check prints true because the file now exists. The read call then prints the stored text.
Note
A later read in the same script sees the text from the latest write in that script.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What happens when write is called on a file that already has text?