Julia File
Julia provides some basic functions to handle files:
* open() - Open a file
* read() - Read file content
* close() - Close a file
Reading data from or writing data to a file requires using a file handle.
A file handle is essentially a pointer, which points to a specific location in a file.
To read data from a file, an application must first call an operating system function and pass the filename, choosing a path to that file to open it. The open file function returns a sequence number, which is the file handle. This file handle serves as the 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 filename, **mode** is the read/write mode, which can be one of the following values:
| mode | Description | Keywords |
| --- | --- | --- |
| `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, write, create, append | `append = true, read = true` |
# Windows open file foo = open("D://-test//julia//-file.txt")# Linux or Mac open file foo = open("./-test/julia/-file.txt")
### close() Function
After completing file operations, we need to close the file; otherwise, it may cause resource leaks and other issues. Closing a file uses the **close()** function:
# Close the foo handle returned from opening the file in the code above close(foo)
In Julia, we recommend wrapping any file handling functions in a do block. The advantage of wrapping file handling functions in a do block is that when the block execution completes, the opened file will be closed automatically, meaning the close() function will be called automatically, as shown below:
## Example
open("./-test/julia/-file.txt")do file
# Perform file operations
end
The above code does not need to call the close() function because it will automatically call close() to close the file.
Next, let's create a test.jl file with the following code:
## test.jl File Code:
# Open file, create -file.txt if it doesn't exist
io = open("-file.txt", "w");
# Write file content
write(io, "Hello world!n Julia Test");
# Close file
close(io);
Execute the above code:
$ julia test.jl
After successful execution, a -file.txt file will be created in the current code file directory, with the following content:
Hello world! Julia Test
We can use the do statement, so we don't need to use the **close()** function:
## test.jl File Code:
open("-file.txt", "w")do io
write(io, "Hello world!n Julia Testn Using do statement")
end;
Execute the above code:
$ julia test.jl
After successful execution, a -file.txt file will be created in the current code file directory, with the following content:
Hello world! Julia TestUsing do statement
## Example
# Read file content
txt = open("-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("-file.txt")
# Read file content
txt = read(file, String)
# Close file
close(file)
# Output
println(txt)
Execute the above code, the output is as follows:
$ Julia test.jl Hello world! Julia Test
Using the **read()** function in a do statement:
open(filename) do file read(file, String)end
## Example
# Read file content
txt = open("-file.txt")do file
read(file, String)
end;
# Output
println(txt)
Execute the above code, the output is as follows:
$ julia test.jl Hello world! Julia Test
We can use the **readlines()** function to put file content into an array by line, with the following syntax:
readlines(io::IO=stdin; keep::Bool=false) readlines(filename::AbstractString; keep::Bool=false)
## Example
# Open file
file = open("-file.txt")
# Read file content
txt=readlines(file, keep=true)
# Close file
close(file)
# Output
println(txt)
Execute the above code, the output is as follows:
$ julia test.jl ["Hello world!n", " Julia Testn", "Using do statement"]
We can also use the **eachline()** function to process files line by line:
## Example
# Open file
open("-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
Execute the above code, the output is as follows:
$ julia test.jl 12, Hello world!17, Julia Test8, Using do statement
We can also get the current line number:
## Example
open("-file.txt")do f
# Set line number
line = 1
while!eof(f)
x = readline(f)
println("$line $x")
# Increment line by line
line += 1
end
end
Execute the above code, the output is as follows:
$ julia test.jl 1 Hello world!2 Julia Test3 Using do statement
### stat() Function
**stat()** function is used to get file information, with the following format:
stat(pathname)
## Example
for n in fieldnames(typeof(stat("-file.txt")))
println(n, ": ", getfield(stat("-file.txt"),n))
end
Execute the above code, the output is as follows:
$ julia test.jl desc: -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
**abspath()** function is used to get the absolute path of a file, which can be used with mapping lists:
stat(pathname)
## Example
println(map(abspath, readdir()))
Execute the above code, the output is as follows:
$ julia test.jl ["/Users//-test/.Rhistory", "/Users//-test/.vscode", ...
### More Functions
The following table lists other related functions for handling files:
| No. | Function and Description |
| --- | --- |
| 1 | cd(path) Change current directory |
| 2 | pwd() Get current directory |
| 3 | readdir(path) Returns the list of files and directories in the current directory. |
| 4 | abspath(path) Generate absolute path from the current directory filename. |
| 5 | joinpath(str, str, ...) Assemble path name from parameters. |
| 6 | isdir(path) Check if the provided path parameter path is a directory. |
| 7 | splitdir(path) Split path into a tuple of directory name and filename. |
| 8 | splitdrive(path) On Windows, split path into drive letter part and 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 the dot and after. 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 path, remove "." and ".." directories |
| 12 | realpath(path) Normalize path from symbolic links, and remove "." and ".." directories |
| 13 | homedir() Get the current user's home directory. |
| 14 | dirname(path) Get the directory part of the path parameter path |
| 15 | basename(path) Get the filename part of the path parameter path. |
YouTip