Easy Tutorial
❮ Julia Repl Julia Mathematical Functions ❯

Julia File Handling

Julia provides some basic functions to handle files:

Reading from or writing to a file requires the use of a file handle.

A file handle is essentially a pointer, which points to a specific location in the file.

To read data from a file, the application first calls an operating system function, passing the file name and selecting a path to the file to open it. The open function returns a sequence number, known as the file handle, which is a unique identifier for the opened file.

open() Function

Julia can use the open() function to open a file, which returns a file handle:

Syntax:

open(filename, mode)

filename is the file name, and mode is the read/write mode, which can be one of the following values:

mode Description Keyword
r read none
w write, create, truncate write = true
a write, create, append append = true
r+ read, write read = true, write = true
w+ read, write, create, truncate truncate = true, read = true
a+ read, write, create, append append = true, read = true

Example:

# Windows open file
foo = open("D://tutorialpro-test//julia//tutorialpro-file.txt")

# Linux or Mac open file
foo = open("./tutorialpro-test/julia/tutorialpro-file.txt")

close() Function

After completing file operations, we need to close the file to avoid resource leaks. Close the file using the close() function:

# Close the file handle foo returned from the previous code
close(foo)

In Julia, it is recommended to wrap any file processing functions in a do block. The advantage of wrapping file processing functions in a do block is that the opened file will be automatically closed when the block completes, invoking the close() function automatically, as shown below:

Example

open("./tutorialpro-test/julia/tutorialpro-file.txt") do file
   # Perform file operations
end

The above code does not require a call to the close() function as it will automatically close the file.

Next, we create a test.jl file with the following code:

test.jl File Code:

# Open file, create tutorialpro-file.txt if it does not exist
io = open("tutorialpro-file.txt", "w");

# Write to file
write(io, "Hello world!\ntutorialpro Julia Test");

# Close file
close(io);

Execute the above code:

$ julia test.jl

Upon successful execution, a tutorialpro-file.txt file is created in the directory of the current code file with the following content:

Hello world!
tutorialpro Julia Test

We can use the do statement, which eliminates the need for the close() function:

test.jl File Code:

open("tutorialpro-file.txt", "w") do io
    write(io, "Hello world!\ntutorialpro Julia Test\nUsing do statement")
end;

Execute the above code:

$ julia test.jl

Upon successful execution, a tutorialpro-file.txt file is created in the directory of the current code file with the following content:

Hello world!
tutorialpro Julia Test
Using do statement

Example

# Read file content
txt = open("tutorialpro-file.txt") do file
    read(file, String)
end;
# Output
println(txt)

read() Function

Using the read() function, we can read the entire content of a file, for example:

txt = read(foo, String)

Example

# Open file
file = open("tutorialpro-file.txt")
# Read file content
txt = read(file, String)

# Close file
close(file)

# Output
println(txt)

Executing the above code, the output is as follows:

$ Julia test.jl
Hello world!
tutorialpro Julia Test

Using the read() function within a do statement:

open(filename) do file
    read(file, String)
end

Example

# Read file content
txt = open("tutorialpro-file.txt") do file
    read(file, String)
end;
# Output
println(txt)

Executing the above code, the output is as follows:

$ julia test.jl
Hello world!
tutorialpro Julia Test

We can use the readlines() function to place file content into an array line by line, with the syntax as follows:

readlines(io::IO=stdin; keep::Bool=false)
readlines(filename::AbstractString; keep::Bool=false)

Example

# Open file
file = open("tutorialpro-file.txt")

# Read file content
txt = readlines(file, keep=true)

# Close file
close(file)

# Output
println(txt)

Executing the above code, the output is as follows:

$ julia test.jl
["Hello world!\n", "tutorialpro Julia Test\n", "Using do statement"]

We can also process files line by line using the eachline() function:

Example

# Open file
open("tutorialpro-file.txt") do file
# Read file content line by line
    for ln in eachline(file)
        # Output string length and string
        println("$(length(ln)), $(ln)")
    end
end

Executing the above code, the output is as follows:

$ julia test.jl
12, Hello world!
17, tutorialpro Julia Test
8, Using do statement

We can also get the current line number:

Example

open("tutorialpro-file.txt") do f
    # Set line number
    line = 1
    while !eof(f)
       x = readline(f)
       println("$line $x")
       # Increment line number
       line += 1
    end
end

Executing the above code, the output is as follows:

$ julia test.jl
1 Hello world!
2 tutorialpro Julia Test
3 Using do statement

stat() Function

The stat() function is used to get file information, with the format as follows:

stat(pathname)

Example

for n in fieldnames(typeof(stat("tutorialpro-file.txt")))
    println(n, ": ", getfield(stat("tutorialpro-file.txt"),n))
end

Executing the above code, the output is as follows:

$ julia test.jl
desc: tutorialpro-file.txt
device: 16777222
inode: 35345094
mode: 33188
nlink: 1
uid: 501
gid: 20
rdev: 0
size: 47
blksize: 4096
blocks: 8
mtime: 1.6524042534674733e9
ctime: 1.6524042534674733e9

abspath() Function

The abspath() function is used to get the absolute path of a file, which can be mapped in a list:

stat(pathname)

Example

println(map(abspath, readdir()))

Executing the above code, the output is as follows:

["/Users/tutorialpro/tutorialpro-test/.Rhistory", "/Users/tutorialpro/tutorialpro-test/.vscode", 
...

More Functions

The following table lists other relevant functions for file processing:

No. Function and Description
1 cd(path) Change the current directory
2 pwd() Get the current directory
3 readdir(path) Return the list of files and directories in the current directory.
4 abspath(path) Generate the absolute path for the file name in the current directory.
5 joinpath(str, str, ...) Assemble a pathname from the arguments.
6 isdir(path) Determine if the provided path parameter is a directory.
7 splitdir(path) Split the path into a tuple of directory name and file name.
8 splitdrive(path) On Windows, split the path into the drive letter part and the path part. On Unix systems, the first component is always an empty string.
9 splitext(path) If the last component of the path contains a dot, split the path into everything before the dot and everything including and after the dot. Otherwise, return a tuple of the unmodified argument and an empty string.
10 expanduser(path) Replace the tilde character at the beginning of the path with the current user's home directory.
11 normpath(path) Normalize the path, removing "." and ".." directories.
12 realpath(path) Normalize the path if symbolic links are present, and remove "." and ".." directories.
13 homedir() Get the home directory of the current user.
14 dirname(path) Get the directory part of the path parameter.
15 basename(path) Get the file name part of the path parameter.
❮ Julia Repl Julia Mathematical Functions ❯