Julia File Read/Write

Julia provides some basic functions to handle files:

  • open()- Open file
  • read()- Read file content
  • close()- Close file

To read or write data from a file, you need to use a file handle.

A file handle is actually a pointer, and the pointer points to a certain position in the file.

To read data from a file, the application first calls an operating system function, passes the file name, and selects a path to the file to open it. The function that opens the file returns a sequence number, i.e., the file handle. This file handle is the unique identifier for the opened file.

open() Function

Julia can useopen()function to open a file, this function returns a file handle:

Syntax format:

open(filename, mode)

filenameis the file name,modeis the read/write mode, which can be 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
# Windows 打开文件
foo = open("D://example-test//julia//example-file.txt")

# Linux 或 Mac 打开文件 
foo = open("./example-test/julia/example-file.txt")

close() Function

After finishing file operations, we need to close the file; otherwise it may cause problems such as resource leaks. To close a file, useclose()function:

# 关闭上面代码中打开文件返回的 foo 句柄
close(foo)

In Julia, we recommend that any file processing function be wrapped in adostatement block. The advantage of wrapping file processing functions in a do statement block is that when the block finishes execution, the opened file will be automatically closed, i.e., it will automatically call the close() function, as shown below:

Example

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

The above code does not need to call the close() function, because it will automatically call the close() function to close the file.

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

test.jl file code:

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

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

# Close the file
close(io);

Execute the above code:

$ julia test.jl

After successful execution, a example-file.txt file is created in the directory of the current code file, and the written content is as follows:

Hello world!
Example Julia Test

We can usedostatement, so there is no need to useclose()function:

test.jl file code:

open("example-file.txt", "w") do io
    write(io, "Hello world!\nExample Julia Test\nUse do statement)
end;

Execute the above code:

$ julia test.jl

After successful execution, a example-file.txt file is created in the directory of the current code file, and the written content is as follows:

Hello world!
Example Julia Test
使用 do 语句

Example

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

read() Function

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

txt = read(foo, String)

Example

# Open the file
file = open("example-file.txt")

# Read file content
txt = read(file, String)

# Close the file
close(file)

# Output
println(txt)

Execute the above code, the output result is as follows:

$ Julia test.jl
Hello world!
Example Julia Test

doIn the statement, useread()function:

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

Example

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

Execute the above code, the output result is as follows:

$ julia test.jl
Hello world!
Example Julia Test

We can usereadlines()function to put the file content into an array line by line, with the following syntax:

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

Example

# Open the file
file = open("example-file.txt")

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

# Close the file
close(file)

# Output
println(txt)

Execute the above code, the output result is as follows:

$ julia test.jl
["Hello world!\n", "Example Julia Test\n", "使用 do 语句"]

We can also useeachline()function to process the file line by line:

Example

# Open the file
open("example-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 result is as follows:

$ julia test.jl
12, Hello world!
17, Example Julia Test
8, 使用 do 语句

We can also get the current line number:

Example

open("example-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 result is as follows:

$ julia test.jl
1 Hello world!
2 Example Julia Test
3 使用 do 语句

stat() Function

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

stat(pathname) 

Example

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

Execute the above code, the output result is as follows:

$ julia test.jl
desc: example-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() The function is used to get the absolute path of a file, and can be mapped to a list:

stat(pathname) 

Example

println(map(abspath, readdir()))

Execute the above code, the output result is as follows:

["/Users/EXAMPLE/example-test/.Rhistory", "/Users/EXAMPLE/example-test/.vscode", 
...

More 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 the list of files and directories in the current directory.

4

abspath(path)

Generate absolute paths from file names in the current directory.

5

joinpath(str, str, ...)

Assemble a path name from arguments.

6

isdir(path)

Determine whether the given path parameter `path` 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 a drive letter part and a 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 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)

Follow symbolic links to normalize the path, 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 `path`.

15

basename(path)

Get the file name part of the path parameter `path`.

Other Extensions