I/O, Files & Networking
Also: JLD2.jl (HDF5-based Julia data), HDF5.jl, Arrow.jl, Parquet2.jl, BSON.jl, TOML (stdlib), YAML.jl.
20.1 Console
println("text"); print("no newline"); show(1:3); display([1 2; 3 4])
print(stderr, "error output\n")
name = readline() # read a line from stdin
n = parse(Int, readline())20.2 Files
write("out.txt", "Hello\nWorld\n") # write whole file
s = read("out.txt", String) # read whole file
lines = readlines("out.txt")
for line in eachline("out.txt") # lazily, line by line
println(uppercase(line))
end
open("log.txt", "a") do io # append; file closed automatically
println(io, "entry at ", time())
write(io, "raw text\n")
end
open("data.bin", "w") do io # binary I/O
write(io, Int64(42), 3.14)
end
open("data.bin") do io
a = read(io, Int64); b = read(io, Float64)
end
io = IOBuffer(); print(io, "in memory"); String(take!(io))
sprint(show, [1, 2])20.3 Filesystem
pwd(), cd("dir"), readdir("."), mkdir("new"), mkpath("a/b/c")
isfile("x"), isdir("y"), ispath("z"), filesize("x"), mtime("x")
rm("x"), rm("dir"; recursive=true), mv("a", "b"), cp("a", "b"; force=true)
joinpath("data", "raw", "f.csv"), basename(p), dirname(p), splitext("f.csv"), abspath("x")
homedir(), tempdir(), tempname(), mktempdir()
walkdir(".") |> collect
@__DIR__, @__FILE__ # location of the current source file20.4 Running external commands
run(`ls -l`) # backticks create Cmd objects (no shell)
out = read(`git status`, String)
success(`which python`)
file = "my file.txt"; run(`cat $file`) # safe interpolation (no injection)
pipeline(`ls`, `grep jl`) |> run
run(pipeline(`echo hi`, stdout="out.txt"))20.5 Delimited files, serialization, JSON
Also: JLD2.jl (HDF5-based Julia data), HDF5.jl, Arrow.jl, Parquet2.jl, BSON.jl, TOML (stdlib), YAML.jl.
using DelimitedFiles
writedlm("m.csv", rand(3, 3), ','); readdlm("m.csv", ',')
using Serialization
serialize("obj.jls", Dict(:a => 1)); deserialize("obj.jls")
using JSON3 # or JSON.jl
JSON3.write(Dict("a" => [1, 2]))
obj = JSON3.read("""{"name": "Ann", "age": 30}"""); obj.name20.6 Networking
using Downloads
Downloads.download("https://julialang.org", "julia.html")
using HTTP
r = HTTP.get("https://api.github.com/repos/JuliaLang/julia")
r.status; JSON3.read(r.body).stargazers_count
using Sockets
server = listen(8080)
@async while true
sock = accept(server)
@async (println(sock, "echo: ", readline(sock)); close(sock))
end