Julia File I/O
Julia provides simple yet powerful file I/O operations, supporting both text and binary file reading and writing.
Opening and Closing Files
Basic File Operations
julia
# Open file
f = open("test.txt", "w") # Write mode
write(f, "Hello, Julia!")
close(f)
# Using do syntax (recommended, auto-closes)
open("test.txt", "w") do f
write(f, "Hello, Julia!\n")
write(f, "This is a test.")
endFile Modes
| Mode | Description |
|---|---|
"r" | Read (default) |
"w" | Write (overwrite) |
"a" | Append |
"r+" | Read and write |
"w+" | Read and write (overwrite) |
"a+" | Read and write (append) |
julia
# Read mode
f = open("test.txt", "r")
content = read(f, String)
close(f)
# Append mode
open("test.txt", "a") do f
write(f, "\nAppended line.")
endReading Files
Read Entire File
julia
# Read as string
content = read("test.txt", String)
println(content)
# Read as byte array
bytes = read("test.txt")
println(bytes)
# Using open + do
content = open("test.txt") do f
read(f, String)
endRead Line by Line
julia
# Read all lines (including newlines)
lines = readlines("test.txt")
for line in lines
println(line)
end
# Read all lines (without newlines, default)
lines = readlines("test.txt", keep=false)
# Read line by line (more memory efficient)
open("test.txt") do f
for line in eachline(f)
println(line)
end
end
# Use eachline directly on file
for line in eachline("test.txt")
println(line)
endRead Partial Content
julia
open("test.txt") do f
# Read specified number of bytes
chunk = read(f, 10) # Read 10 bytes
println(String(chunk))
# Read one line
line = readline(f)
println(line)
# Read one character
c = read(f, Char)
println(c)
endWriting Files
Write Strings
julia
# Simple write
write("output.txt", "Hello, World!")
# Using open
open("output.txt", "w") do f
write(f, "Line 1\n")
write(f, "Line 2\n")
end
# Using print and println
open("output.txt", "w") do f
println(f, "This is line 1")
println(f, "This is line 2")
print(f, "No newline at end")
endWrite Multiple Lines
julia
lines = ["Apple", "Banana", "Cherry"]
# Method 1: Write line by line
open("fruits.txt", "w") do f
for line in lines
println(f, line)
end
end
# Method 2: Using join
open("fruits.txt", "w") do f
write(f, join(lines, "\n"))
end
# Method 3: Using writedlm
using DelimitedFiles
writedlm("fruits.txt", lines)Append Write
julia
# Append mode
open("log.txt", "a") do f
println(f, "$(now()): New log entry")
endCSV and Delimited Files
Using DelimitedFiles
julia
using DelimitedFiles
# Write CSV
data = [1 2 3; 4 5 6; 7 8 9]
writedlm("data.csv", data, ',')
# Read CSV
data = readdlm("data.csv", ',', Int)
println(data)
# CSV with headers
headers = ["A" "B" "C"]
data = [1 2 3; 4 5 6]
open("data_with_header.csv", "w") do f
writedlm(f, headers, ',')
writedlm(f, data, ',')
end
# Read CSV with headers
content = readdlm("data_with_header.csv", ',', header=true)
data = content[1]
headers = content[2]Using CSV.jl (Recommended)
julia
using CSV
using DataFrames
# Read CSV
df = CSV.read("data.csv", DataFrame)
println(df)
# Write CSV
CSV.write("output.csv", df)
# With options
df = CSV.read("data.csv", DataFrame,
delim=',',
header=true,
missingstring="NA"
)JSON Files
julia
using JSON
# Write JSON
data = Dict(
"name" => "Julia",
"version" => 1.10,
"features" => ["fast", "dynamic", "easy"]
)
open("data.json", "w") do f
JSON.print(f, data, 4) # 4 is indent
end
# Read JSON
data = open("data.json") do f
JSON.parse(f)
end
println(data["name"])
# Simple read
data = JSON.parsefile("data.json")Binary Files
Read and Write Binary Data
julia
# Write binary
arr = [1.0, 2.0, 3.0, 4.0, 5.0]
open("data.bin", "w") do f
write(f, arr)
end
# Read binary
arr = zeros(Float64, 5)
open("data.bin") do f
read!(f, arr)
end
println(arr)
# Read specific type
open("data.bin") do f
values = Vector{Float64}(undef, 5)
read!(f, values)
println(values)
endSerialization
julia
using Serialization
# Serialize Julia objects
data = Dict("a" => [1, 2, 3], "b" => "hello")
serialize("data.jls", data)
# Deserialize
data = deserialize("data.jls")
println(data)File and Directory Operations
Path Operations
julia
# Path joining
path = joinpath("folder", "subfolder", "file.txt")
println(path)
# Get directory name
println(dirname("/home/user/file.txt")) # /home/user
# Get filename
println(basename("/home/user/file.txt")) # file.txt
# Get extension
println(splitext("file.txt")) # ("file", ".txt")
# Absolute path
println(abspath("file.txt"))
# Current directory
println(pwd())
# Change directory
cd("some_directory")File Checking
julia
# Check if file exists
println(isfile("test.txt"))
# Check if directory exists
println(isdir("some_folder"))
# Check if path exists
println(ispath("test.txt"))
# File size
println(filesize("test.txt"))
# Modification time
println(mtime("test.txt"))Directory Operations
julia
# Create directory
mkdir("new_folder")
mkpath("path/to/nested/folder") # Create nested directories
# List directory contents
files = readdir(".")
println(files)
# List directory (with full paths)
files = readdir(".", join=true)
# Walk directory tree
for (root, dirs, files) in walkdir(".")
for file in files
println(joinpath(root, file))
end
endFile Operations
julia
# Copy file
cp("source.txt", "destination.txt")
# Move/rename file
mv("old_name.txt", "new_name.txt")
# Delete file
rm("file.txt")
# Delete directory
rm("folder", recursive=true)
# Create temporary file
temp_path, temp_io = mktemp()
write(temp_io, "Temporary content")
close(temp_io)
println(temp_path)
# Create temporary directory
temp_dir = mktempdir()
println(temp_dir)Practical Examples
Configuration File Reading
julia
function read_config(filename)
config = Dict{String, String}()
for line in eachline(filename)
line = strip(line)
# Skip empty lines and comments
isempty(line) && continue
startswith(line, '#') && continue
# Parse key=value
if occursin('=', line)
key, value = split(line, '=', limit=2)
config[strip(key)] = strip(value)
end
end
return config
end
# config.ini:
# host=localhost
# port=8080
# debug=trueLogger
julia
function log_message(filename, level, message)
open(filename, "a") do f
timestamp = Dates.format(now(), "yyyy-mm-dd HH:MM:SS")
println(f, "[$timestamp] [$level] $message")
end
end
log_message("app.log", "INFO", "Application started")
log_message("app.log", "ERROR", "Something went wrong")Batch File Processing
julia
function process_all_txt_files(directory)
for file in readdir(directory)
if endswith(file, ".txt")
filepath = joinpath(directory, file)
content = read(filepath, String)
# Process content
println("Processing: $file ($(length(content)) characters)")
end
end
endLarge File Processing
julia
function count_lines(filename)
count = 0
for _ in eachline(filename)
count += 1
end
return count
end
function process_large_file(input, output)
open(output, "w") do out
for line in eachline(input)
# Process each line
processed = uppercase(line)
println(out, processed)
end
end
endIO Streams
String IO
julia
# Write to IOBuffer
io = IOBuffer()
print(io, "Hello, ")
print(io, "World!")
content = String(take!(io))
println(content) # "Hello, World!"
# Read from string
io = IOBuffer("Line 1\nLine 2\nLine 3")
for line in eachline(io)
println(line)
endPipes
julia
# Read command output
output = read(`ls -la`, String)
println(output)
# Write to command
open(`sort`, "w", stdout) do io
println(io, "banana")
println(io, "apple")
println(io, "cherry")
endNext Steps
After learning file I/O, continue with:
- Strings - Text processing
- Regular Expressions - File content parsing
- Date and Time - Log timestamps