iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔡

How to read text files in Julia

に公開
2026/04/12

I wrote this article because I couldn't find any straightforward articles when Googling "Julia read text file." We will read the following file.

hello.txt
Hello World!

Here is the Julia code to read the file above and store it in the string variable text.

load.jl
# Open the file in read mode
file = open("./hello.txt", "r")
# Read the contents into a String
text = Base.read(file, String)
# Close the file
close(file)
println(text)

I realized that it can be written more concisely as follows (2026/4/12). It seems that the behavior is changed based on the type of the argument through multiple dispatch.

load.jl
text = Base.read("./hello.txt", String)
println(text)

You can run this in the REPL or a Notebook, but you can also execute it as follows:

Execution method
julia load.jl

The contents of hello.txt should be read.

Output
Hello World!

The two files mentioned above have been placed in a Gist.

https://gist.github.com/ohno/949bbd364ca53643723e91477fd5561b

References are as follows:

Discussion