Elixir Files
A file is data stored on disk under a name. The File module writes text to a file and reads it back.
Write a file, then read it back
The write happens first in the same block. The read then returns exactly the text that was written.
File.write!("notes.txt", "Hello, file")
IO.puts(File.read!("notes.txt"))File.read returns a result tuple
The plain read answers with a tuple instead of the raw text. A successful read starts with :ok.
File.write!("data.txt", "Elixir")
IO.inspect(File.read("data.txt"))A missing file returns :enoent
The name never-created.txt is never written in this block, so it stays missing. The exists check agrees, while the written file checks true.
File.write!("present.txt", "here")
IO.puts(File.exists?("present.txt"))
IO.inspect(File.read("never-created.txt"))
IO.puts(File.exists?("never-created.txt"))Example
File.write!("profile.txt", "Ana,31")
text = File.read!("profile.txt")
[name, age] = String.split(text, ",")
IO.puts("Name: #{name}")
IO.puts("Age: #{age}")Key points
- Write: File.write!(name, text) creates the file or replaces its whole content.
- Read back: File.read!(name) returns the content of the file as a string.
- Result form: File.read(name) returns {:ok, text} when the file exists.
- Missing file: File.read returns {:error, :enoent}, where :enoent means no file has that name.
- Exists check: File.exists?(name) returns true or false without reading the file.
- Names: a plain name like "notes.txt" means a file in the current folder.
In this example, the block writes one line of text to profile.txt and reads it straight back. String.split breaks the text at the comma, and the two printed lines show the name and age that were stored.
Note
the bang forms write! and read! raise on failure, while the plain read returns a result tuple.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does File.read("never-created.txt") return when no file has that name?