Elixir basics · Lesson 19 (open contents)
Read and write one real file
Build a path, write UTF-8 text, and handle the tagged read result.
Run this first
Run it once, change one input, and compare the new result.
# Write and read one temporary UTF-8 file
path = Path.join(System.tmp_dir!(), "beam-path-note.txt")
:ok = File.write(path, "north
south
")
{:ok, text} = File.read(path)
{path, String.split(text, "
", trim: true)}- The tuple contains the temporary path and
["north", "south"].
Read from the first line down
- Read
Path.join/2: Join path segments for the current operating system. - Read
File.write/2: Write bytes and return a tagged result. - Read
File.read/1: Read the file and return tagged data.
Symbols are not secret signs
Path.join/2Join path segments for the current operating system.
File.write/2Write bytes and return a tagged result.
File.read/1Read the file and return tagged data.
Match each name to its meaning
path
Path.join/2 builds a platform-safe path instead of joining strings by hand.
tagged file result
Non-bang File functions return {:ok, data} or {:error, reason}.
resource boundary
Files belong outside pure transformation functions so errors and cleanup stay visible.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
Path.join/2 builds a platform-safe path instead of joining strings by hand.
Non-bang File functions return {:ok, data} or {:error, reason}.
Close the answer and try
Append east to the same file and read it again.
:ok = File.write(path, "east
", ____)
File.read(path)Target result: Use append mode and receive {:ok, text}.
Stuck? Read one hint
Pass [:append] as the third argument.
After you run it, see one answer
:ok = File.write(path, "east
", [:append])
File.read(path)Think about it: Why use `Path.join` instead of a hard-coded slash?
It builds a valid path on different operating systems.
Remember these three lines
- 1
Build paths with Path.
- 2
Keep file errors tagged.
- 3
Separate file access from pure data cleanup.