liveBook · Manning

Open

As explained in Julia as a Second Language

open is a Julia function that establishes access to a file or other stream and returns an associated IO object.

open establishes access to a file, command, or other stream and returns an IO object. Use that object with functions such as print, println, readuntil, or join; close it when the operation is complete. section 5.0 section 5.5

The same function supports several practical I/O patterns:

  • Call open(path) to open a file for reading; pass "w" to open it for writing. section 17.4.2
  • Pass a do-end function so Julia receives the IO object and closes it automatically afterward. section 17.4.2
  • Call open on a command object to execute a command and receive a Process connection whose output can be read like a file. section 17.2

Save structured rows to a file

function save_engines(path::AbstractString, engines) open(path, "w") do io println(io, "name,company,mass,thrust,Isp") for (name, egn) in engines row = [name, "", egn.mass, egn.thrust, egn.Isp] join(io, row, ',') println(io) end end end The IO argument directs println and join to the file instead of standard output, while the do-end form handles closing. section 17.4.2

shell> grep "Rocket Lab" rocket-engines.csv
Curie,Rocket Lab,0.008,0.12,317
Rutherford,Rocket Lab,0.035,25,311

julia> io = open(`grep "Rocket Lab" rocket-engines.csv`);

julia> readuntil(io, ',')
"Curie"

julia> readuntil(io, ',')
"Rocket Lab"

julia> readuntil(io, ',')
"0.008"

julia> position(io)
ERROR: MethodError: no method matching position(::Base.Process)

julia> close(io)

Inspect an interactive example where open runs grep, returns a Process connection, and lets readuntil consume the command output. section 17.2

How Julia as a Second Language covers it

How deep it goes
Covers reading, writing, automatic closing, command execution, and the distinction between Process and IOStream capabilities.
Examples
Uses formatted text files, rocket-engine CSV output, and Unix grep output consumed through a Process connection.
What you can do after
Apply it via Julia to read files, write structured output, or consume output from an external process.
How it connects
Links IO objects, print, println, readuntil, close, command objects, processes, and do-end functions.

Also explained in

Compare how 9 books explain open →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.