File reading/writing is similar to other languages where you first
open the file, specify the modality (
w write or
a append) and bind the file to an object, and finally operate on this object and
close() it when you are done.
A better alternative is however to encapsulate the file operations in a
do block that closes the file automatically when the block ends:
open("afile.txt", "w") do f # "w" for writingwrite(f, "test\n") # \n for newlineend
Read the whole file in a single operation:
open("afile.txt", "r") do f # "r" for readingfilecontent = read(f,String) # attention that it can be used only once. The second time, without reopening the file, read() would return an empty stringprint(filecontent)end
or, reading line by line:
open("afile.txt", "r") do ffor ln in eachline(f)println(ln)endend
or, if you want to keep track of the line numbers:
open("afile.txt", "r") do ffor (i,ln) in enumerate(eachline(f))println("$i $ln")endend
Some packages that deals with IO are:
Some basic examples that use them are available in the DataFrame section.
While an updated, expanded and revised version of this chapter is available in "Chapter 5 - Input/Output" of Antonello Lobianco (2019), "Julia Quick Syntax Reference", Apress, this tutorial remains in active development.