Julia File Reading and Writing
Julia provides some basic functions for handling files:
- open() - open a file
- read() - read file contents
- write() - write content
- close() - close a file
Reading data from or writing data to a file requires a file handle.
A file handle is actually a pointer that points to a certain position in the file. To read data from a file, an application first calls an operating system function and passes the file name to open the file; the function that opens the file returns a sequential number, namely the file handle, which is the unique identifier for the opened file.
The open() function
Julia can use open() function to open a file; this function returns a file handle:
Syntax format:
open(filename, mode)
filename is the file name,mode is the read/write mode, which can be the following values:
| mode(mode) | Description | Keyword |
|---|---|---|
r |
Read (default mode) | 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 |
# Open file in Windows
foo = open("D://runoob-test//julia//runoob-file.txt")
# Open file on Linux or Mac
foo = open("./runoob-test/julia/runoob-file.txt")
The close() function
After finishing operations on a file, we need to close it; otherwise problems such as resource leaks may occur. To close a file use close() functions as follows:
# Close the foo handle returned by the file opened in the code above
close(foo)
In Julia, we recommend wrapping file handling in a do block: when the block finishes executing, the opened file is closed automatically (the close() function is called automatically), guaranteeing closure even if an exception is thrown midway:
Example
open
(
"./runoob-test/julia/runoob-file.txt"
)
do
file
Perform file operations
end
Writing to a File
Basic flow for creating and writing a file: open with the "w" mode (creates the file if it does not exist, clears it if it does), write writes, close closes:
test.jl file code
Open the file, creating runoob-file.txt if it does not exist
io =
open
(
"runoob-file.txt"
,
"w"
)
;
Write the file content
write
(
io,
"Hello world!\nRunoob Julia Test"
)
;
Close the file (the content is actually flushed to disk only after closing)
close
(
io
)
;
Execute the above code:
$ julia test.jl
After successful execution, we have created a runoob-file.txt file in the directory of the current code file, with the following content written:
Hello world!
Runoob Julia Test
Using a do block removes the need to close manually:
test.jl file code
open
(
"runoob-file.txt"
,
"w"
)
do
io
write
(
io,
"Hello world!\nRunoob Julia Test\nusing a do block"
)
end
;
A simpler way: write the file directly with the write method, which automatically opens and closes the file internally:
Example
write(filename, content) completes writing in one line
julia
write
(
"runoob-file.txt"
,
"Hello world!\nRUNOOB"
)
17
The return value of write is the number of bytes written.
Append mode:Opening with the "a" mode appends content to the end of the file without clearing the original content: open("runoob-file.txt", "a") do io; write(io, "a new line\n"); end
Reading a file
The read() function
Using the read() function, we can read the entire content of a file:
Example
Opening a File
file =
open
(
"runoob-file.txt"
)
Read the file content as a string
txt = read
(
file,
String
)
Closing a File
close
(
file
)
Output
println
(
txt
)
After executing the above code, the output is as follows:
$ julia test.jl
Hello world!
Runoob Julia Test
Using the read() function in a do block:
Example
Read the file content; the do block closes automatically when it ends
txt =
open
(
"runoob-file.txt"
)
do
file
read
(
file,
String
)
end
;
Output
println
(
txt
)
There is an even more concise form: read accepts the file name directly:
Example
read(filename, String) completes reading in one line
julia
txt = read
(
"runoob-file.txt"
,
String
)
;
The readlines() function
We can use the readlines() The function puts the file content into an array line by line:
readlines(io; keep::Bool=false)
readlines(filename; keep::Bool=false)
Example
Opening a File
file =
open
(
"runoob-file.txt"
)
Read the file content; keep=true preserves the trailing newline of each line
txt = readlines
(
file, keep=
true
)
Closing a File
close
(
file
)
Output
println
(
txt
)
After executing the above code, the output is as follows:
$ julia test.jl
["Hello world!\n", "Runoob Julia Test\n", "使用 do 语句"]
eachline() processes line by line
For large files, use eachline() reading line by line to avoid loading the entire file into memory at once:
Example
open
(
"runoob-file.txt"
)
do
file
Read the file content line by line
for
ln
in
eachline
(
file
)
Output the string length and the string
println
(
"$(length(ln)), $(ln)"
)
end
end
After executing the above code, the output is as follows:
$ julia test.jl
12, Hello world!
17, Runoob Julia Test
8, 使用 do 语句
We can also get the current line number:
Example
open
(
"runoob-file.txt"
)
do
f
Set the line number
line =
1
while
!
eof
(
f
)
x = readline
(
f
)
println
(
"$line $x"
)
Increment line by line
line +=
1
end
end
After executing the above code, the output is as follows:
$ julia test.jl
1 Hello world!
2 Runoob Julia Test
3 使用 do 语句
The stat() function
stat() The function is used to get information about a file:
stat(pathname)
Example
for
n
in
fieldnames
(
typeof
(
stat
(
"runoob-file.txt"
)
)
)
println
(
n,
": "
, getfield
(
stat
(
"runoob-file.txt"
)
, n
)
)
end
After executing the above code, the output is as follows:
$ julia test.jl
desc: runoob-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
Common shortcut field functions include filesize(path) (file size), isfile(path) (whether it is a file), isdir(path) (whether it is a directory), etc.
The abspath() function
abspath() The function is used to convert a relative path to an absolute path:
abspath(path)
Example
Convert all file names in the current directory to absolute paths
println
(
map
(
abspath,
readdir
(
)
)
)
After executing the above code, the output is as follows:
["/Users/RUNOOB/runoob-test/.Rhistory", "/Users/RUNOOB/runoob-test/.vscode",
...
File and path operation functions
The following table lists other related functions for handling files:
| No. | Function and description |
|---|---|
| 1 |
cd(path) Change the current directory |
| 2 |
pwd() Get the current directory |
| 3 |
readdir(path) Return a list of file and subdirectory names under a directory |
| 4 |
abspath(path) Convert a relative path to an absolute path |
| 5 |
joinpath(str, str, ...) Assemble a path name from arguments (automatically handling separators, cross-platform) |
| 6 |
isdir(path) Determine whether the provided path argument path is a directory |
| 7 |
splitdir(path) Split a path into a tuple of directory name and file name |
| 8 |
splitdrive(path) On Windows, split a path into a drive letter part and a path part; on Unix systems, the first component is always an empty string |
| 9 |
splitext(path) Split a path into the part before the extension and the extension (including the dot); when there is no extension, the second part is an empty string |
| 10 |
expanduser(path) Replace the leading tilde character ~ in a path with the current user's home directory |
| 11 |
normpath(path) Normalize a path, removing "." and ".." directories |
| 12 |
realpath(path) Resolve symbolic links and normalize the path, removing "." and ".." directories |
| 13 |
homedir() Get the current user's home directory |
| 14 |
dirname(path) Get the directory part of the path argument path |
| 15 |
basename(path) Get the file name part of the path argument path |
| 16 |
cp(src, dst) Copy a file or directory |
| 17 |
mv(src, dst) Move (rename) a file or directory |
| 18 |
rm(path) Delete a file (deleting a directory requires recursive=true) |
| 19 |
mkdir(path) / mkpath(path) Create a directory / recursively create multi-level directories |
| 20 |
download(url) Download a network file to local |
Example: common file operations
Create a directory
mkpath
(
"runoob/data"
)
Cross-platform path joining
path = joinpath
(
"runoob"
,
"data"
,
"test.txt"
)
Copy a file
cp
(
"runoob-file.txt"
, path
;
force=
true
)
Check whether the file exists
println
(
isfile
(
path
)
)
true
Delete a directory and its contents
rm
(
"runoob"
;
recursive=
true
)