文件操作 #
一、读写文本文件 #
1.1 读取整个文件 #
julia
content = read("file.txt", String)
1.2 逐行读取 #
julia
for line in eachline("file.txt")
println(line)
end
1.3 读取所有行 #
julia
lines = readlines("file.txt")
1.4 写入文件 #
julia
open("output.txt", "w") do f
write(f, "Hello, Julia!\n")
println(f, "Another line")
end
1.5 追加内容 #
julia
open("output.txt", "a") do f
println(f, "Appended line")
end
二、文件打开模式 #
2.1 模式说明 #
| 模式 | 描述 |
|---|---|
"r" |
只读(默认) |
"w" |
写入(覆盖) |
"a" |
追加 |
"r+" |
读写 |
"w+" |
读写(覆盖) |
2.2 手动打开关闭 #
julia
f = open("file.txt", "r")
content = read(f, String)
close(f)
2.3 do块语法 #
julia
open("file.txt", "r") do f
content = read(f, String)
println(content)
end
三、二进制文件 #
3.1 读取二进制 #
julia
data = read("file.bin")
3.2 写入二进制 #
julia
open("output.bin", "w") do f
write(f, [0x01, 0x02, 0x03, 0x04])
end
3.3 读取特定类型 #
julia
open("data.bin", "r") do f
n = read(f, Int32)
arr = read(f, Float64, n)
end
四、文件系统操作 #
4.1 文件信息 #
julia
s = stat("file.txt")
s.size
s.mtime
s.mode
isfile("file.txt")
isdir("directory")
4.2 创建和删除 #
julia
mkdir("new_directory")
mkpath("path/to/directory")
rm("file.txt")
rm("directory", recursive=true)
4.3 复制和移动 #
julia
cp("source.txt", "dest.txt")
mv("old.txt", "new.txt")
4.4 重命名 #
julia
mv("old_name.txt", "new_name.txt")
五、路径操作 #
5.1 路径拼接 #
julia
joinpath("path", "to", "file.txt")
5.2 路径分解 #
julia
dirname("/path/to/file.txt")
basename("/path/to/file.txt")
splitext("file.txt")
5.3 当前目录 #
julia
pwd()
cd("/new/path")
homedir()
5.4 列出目录 #
julia
readdir(".")
readdir("/path/to/directory")
六、CSV和JSON #
6.1 CSV文件 #
julia
using CSV, DataFrames
df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)
6.2 JSON文件 #
julia
using JSON
data = JSON.parsefile("data.json")
JSON.print("output.json", data)
七、实践练习 #
7.1 练习1:日志文件 #
julia
function write_log(filename, message)
timestamp = Dates.format(now(), "yyyy-mm-dd HH:MM:SS")
open(filename, "a") do f
println(f, "[$timestamp] $message")
end
end
using Dates
write_log("app.log", "Application started")
write_log("app.log", "Processing data")
7.2 练习2:配置文件 #
julia
function load_config(filename)
config = Dict{String, String}()
for line in eachline(filename)
line = strip(line)
isempty(line) || startswith(line, '#') && continue
key, value = split(line, "=", limit=2)
config[strip(key)] = strip(value)
end
return config
end
function save_config(filename, config)
open(filename, "w") do f
for (key, value) in config
println(f, "$key = $value")
end
end
end
7.3 练习3:文件搜索 #
julia
function find_files(directory, pattern)
results = String[]
for (root, dirs, files) in walkdir(directory)
for file in files
if occursin(pattern, file)
push!(results, joinpath(root, file))
end
end
end
return results
end
find_files(".", r"\.jl$")
八、总结 #
本章我们学习了:
- 文本文件:读取和写入
- 文件模式:r、w、a等
- 二进制文件:二进制读写
- 文件系统:创建、删除、复制、移动
- 路径操作:拼接、分解、目录操作
接下来让我们学习Julia的序列化!
最后更新:2026-03-27