ZetCode

Julia Files Tutorial

last modified November 18, 2026

Reading and writing files is one of the most common tasks in a script. Julia keeps the basics simple: write stores data, read retrieves it, and open gives us a file handle, an object through which data flows. Higher-level helpers such as readlines and eachline handle line-oriented text for us.

The examples in this tutorial create their files in the temporary directory /tmp/opencode/julia-file-demo. They are self-contained and can be run repeatedly without changing the repository. All outputs were verified with Julia 1.13.4.

Current Directory: pwd and cd

The pwd function reports the current working directory, the folder relative paths are resolved against. The cd function changes it and accepts a block, in which case the change applies only inside the block. Here we use the plain form and return to the original directory afterwards.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
cd(dir)
println(basename(pwd()))
println(pwd() == dir)
cd("/tmp/opencode")
println(basename(pwd()))

The mkpath function creates the directory if it does not exist, including any missing parent directories, and does nothing if it is already there. After cd(dir), pwd() returns that path, so the equality check prints true. The basename helper extracts the last component of a path, which makes the output short and readable.

$ julia main.jl
julia-file-demo
true
opencode

Building Paths: joinpath, dirname and basename

A path is the address of a file in the directory tree. The joinpath function joins path components with the correct separator for the operating system, so code does not have to hardcode slashes. The dirname and basename functions split a path into its folder and file parts.

main.jl
path = joinpath("/tmp/opencode", "julia-file-demo", "notes.txt")
println(path)
println(dirname(path))
println(basename(path))
println(splitext(basename(path)))

The joined path is an absolute path, meaning it starts at the filesystem root. dirname strips the file name and basename keeps only it. The splitext function separates the name from its extension and returns a two-element tuple, here ("notes", ".txt").

$ julia main.jl
/tmp/opencode/julia-file-demo/notes.txt
/tmp/opencode/julia-file-demo
notes.txt
("notes", ".txt")

Writing and Reading a Whole File

The simplest file operations need no explicit opening or closing. write(path, text) writes the text to the file and creates the file if necessary; if the file exists, its previous content is replaced. read(path, String) reads the whole file into a string.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "hello.txt")
write(path, "Hello, Julia!\n")
print(read(path, String))

The trailing \n in the written text is a newline character, so the file ends with a line break. We use print rather than println to display the file content, otherwise the newline already in the data would produce an extra blank line. The mkpath call makes this script work even on a fresh machine.

$ julia main.jl
Hello, Julia!

Opening and Closing Files Explicitly

For finer control, open returns an input/output stream, often called a handle. The mode "w" opens a file for writing and truncates it, while "r" opens it for reading. A handle should be released with close when we are done with it.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "lines.txt")
io = open(path, "w")
write(io, "first\nsecond\n")
close(io)
io = open(path, "r")
println(readline(io))
println(readline(io))
close(io)

Writing to a handle uses the same write function, with the handle as its first argument. After reopening the file for reading, each call to readline returns the next line without its newline character. The stream remembers its position, which is why the two calls return different lines.

$ julia main.jl
first
second

The do-Block Form of open

Manually closing every handle is easy to forget, especially when an error occurs. The do block form of open passes the handle to a block of code and closes it automatically when the block ends. This is a common Julia idiom.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "do.txt")
open(path, "w") do io
    write(io, "alpha\n")
    write(io, "beta\n")
end
open(path, "r") do io
    for line in eachline(io)
        println(line)
    end
end

The first block writes two lines; the second reads them back. Even if an exception were thrown inside a block, the file would still be closed. The variable io is local to the block, so the two blocks can each use the same name for their handle.

$ julia main.jl
alpha
beta

readlines

The readlines function reads an entire file and returns an array of strings, one per line. By default the newline characters are removed; with keep=true they are preserved.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "list.txt")
write(path, "one\ntwo\nthree\n")
lines = readlines(path)
println(lines)
println(length(lines))
println(readlines(path; keep=true))

The file has three lines, so the array has three elements. With keep=true every element still ends in \n, which is visible in the printed result. Use readlines when the file is small enough to hold in memory and random access to the lines is useful.

$ julia main.jl
["one", "two", "three"]
3
["one\n", "two\n", "three\n"]

eachline

The eachline function is the lazy alternative to readlines: it yields one line at a time instead of building an array. It is a good choice for large files or when we only need to pass over the data once.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "iter.txt")
write(path, "red\ngreen\nblue\n")
for (i, line) in enumerate(eachline(path))
    println("$i: $line")
end

Combining eachline with enumerate gives us both the line number and the text. Only one line is in memory at any moment. Note that eachline removes line endings just like readlines does by default.

$ julia main.jl
1: red
2: green
3: blue

readdir

The readdir function lists the names of the entries in a directory. It returns strings, not full paths, and the order is not guaranteed, so sorting makes the output predictable.

main.jl
dir = "/tmp/opencode/julia-file-demo"
rm(dir; recursive=true, force=true)
mkpath(dir)
for name in ["b.txt", "a.txt", "c.dat"]
    touch(joinpath(dir, name))
end
println(sort(readdir(dir)))
println(sort(filter(endswith(".txt"), readdir(dir))))

We remove the directory first so the script always produces the same three entries, then recreate it. The touch function creates an empty file. The second line uses filter with a predicate to keep only names ending in .txt.

$ julia main.jl
["a.txt", "b.txt", "c.dat"]
["a.txt", "b.txt"]

Checking Files and Directories

Before reading a path it is often useful to ask what kind of entry it is. isfile and isdir return booleans, and filesize reports the size in bytes.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "info.txt")
write(path, "data")
println(isfile(path))
println(isdir(dir))
println(isfile(dir))
println(filesize(path))

The file info.txt exists and the directory exists, but the directory is not a file, hence the third result is false. The four bytes of the word data are reported by filesize. These checks help avoid errors when a path may be missing.

$ julia main.jl
true
true
false
4

Appending to a File

The mode "a" opens a file for appending: new data is written at the end instead of replacing what is already there. If the file does not exist, it is created.

main.jl
dir = "/tmp/opencode/julia-file-demo"
mkpath(dir)
path = joinpath(dir, "append.txt")
open(path, "w") do io
    write(io, "one\n")
end
open(path, "a") do io
    write(io, "two\n")
end
print(read(path, String))

The first block creates the file with the line one. The second block adds two after it, preserving the original content. This is a common pattern for log files and for collecting results in several steps.

$ julia main.jl
one
two

Source

Julia I/O and Network documentation

Julia File System documentation

In this article we have worked with files in Julia: finding the current directory, constructing paths, writing and reading whole files, explicit handles, do blocks, line-oriented reading with readlines and eachline, directory listings, file checks, and appending. Strings are covered in Julia string functions, and iterating over the lines fits with the topics in Julia iterators.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.