Read and write one real file: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Build a path, write UTF-8 text, and handle the tagged read result.
Write two lines to a temporary file, read them back, and count the lines.
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"].
Steps for the full example
- 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.
Original lesson notes
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}.
Symbols and terms
Path.join/2- Join path segments for the current operating system.
File.write/2- Write bytes and return a tagged result.
File.read/1- Read the file and return tagged data.
- path
Path.join/2builds 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.
Original full exercise
Append east to the same file and read it again.
:ok = File.write(path, "east
", ____)
File.read(path)Use append mode and receive {:ok, text}.
Show hint
Pass [:append] as the third argument.
Show original answer
:ok = File.write(path, "east
", [:append])
File.read(path)Why use Path.join instead of a hard-coded slash?
It builds a valid path on different operating systems.
Original lesson takeaways
- Build paths with Path.
- Keep file errors tagged.
- Separate file access from pure data cleanup.