A file line by line
A file of records is read one line at a time in Elixir, and each line becomes a value through a function that is written once. The streams over files lesson showed the call that makes the lines; this page is the rest of the job: the split of a line, the function that answers a value, and the rows of a real file that do not fit.
A stream of lines into rows
A stream of lines hands each line to the next step, so a pipeline trims it, drops the empty one and splits it. The program writes its own file and reads it back:
stream.exs
path = Path.join(System.tmp_dir!(), "people.csv") File.write!(path, "ada,36\nbob,41\n") rows = path |> File.stream!() |> Stream.map(&String.trim/1) |> Stream.reject(&(&1 == "")) |> Enum.map(fn line -> [name, age] = String.split(line, ",") {name, age} end) IO.inspect(rows) File.rm!(path)
elixir stream.exs
[{"ada", "36"}, {"bob", "41"}]
The trim comes before the split because a line from the stream ends with its newline; the reject drops a blank line, which a file often ends with. The last map turns each line into a tuple of text, and a file of ten thousand lines goes through the same four steps.
A parse function that answers a tuple
A file a user gives the program may hold a row that does not fit, so the parse function answers the ok or error tuple instead of crashing. The function below splits the row, parses the number and names the failure it found:
parse.exs
defmodule Row do def parse(line) do case String.split(line, ",") do [name, age] -> case Integer.parse(age) do {number, ""} -> {:ok, {name, number}} _ -> {:error, {:bad_age, line}} end _ -> {:error, {:bad_row, line}} end end end lines = ["ada,36", "bob,x", "broken"] results = Enum.map(lines, &Row.parse/1) IO.inspect(results) IO.puts(Enum.count(results, &match?({:ok, _}, &1)))
elixir parse.exs
[ok: {"ada", 36}, error: {:bad_age, "bob,x"}, error: {:bad_row, "broken"}]
1
The inspector prints a list of ok and error pairs in the keyword form, which is shorter than the tuples it stands for. Integer.parse/1 answers a pair of the number and the rest of the text, so the pattern {number, ""} is what proves the whole field was a number: a parse of "36x" would answer {36, "x"} and fail the pattern.
The good rows and the bad ones
With the parse function in hand, the report of a file is a partition: Enum.split_with/2 answers the rows that parsed and the rows that did not, in one pass and in the order of the file:
split.exs
defmodule Row do def parse(line) do case String.split(line, ",") do [name, age] -> case Integer.parse(age) do {number, ""} -> {:ok, {name, number}} _ -> {:error, {:bad_age, line}} end _ -> {:error, {:bad_row, line}} end end end lines = ["ada,36", "bob,x", "broken"] {good, bad} = Enum.split_with(lines, fn line -> match?({:ok, _}, Row.parse(line)) end) IO.inspect(good) IO.inspect(bad)
elixir split.exs
["ada,36"]
["bob,x", "broken"]
The program parses each line twice, once for the partition and once for the values; a file of a million rows parses each line once and keeps the results, which is the shape a real import takes. The bad rows are printed with the line they came from, so a reader can open the file and fix them.
A whole file, counted
The stream and the partition together are a file read once: the lines arrive, each is parsed, and the two lists hold the answers. The file below has three rows, one of them bad:
count.exs
defmodule Row do def parse(line) do case String.split(line, ",") do [name, age] -> case Integer.parse(age) do {number, ""} -> {:ok, {name, number}} _ -> {:error, {:bad_age, line}} end _ -> {:error, {:bad_row, line}} end end end path = Path.join(System.tmp_dir!(), "people_rows.csv") File.write!(path, "ada,36\nbob,41\nbad,x\n") {good, bad} = path |> File.stream!() |> Stream.map(&String.trim/1) |> Stream.reject(&(&1 == "")) |> Enum.split_with(fn line -> match?({:ok, _}, Row.parse(line)) end) IO.puts(length(good)) IO.inspect(bad) File.rm!(path)
elixir count.exs
2
["bad,x"]
The memory the program uses is the two lists it keeps, not the file: a file of a hundred million rows still holds only the rows it was asked to keep. A report of a million rows that keeps the good ones is a program with a memory problem of its own, and the fix is to count or to write as the stream runs.
The mistake: a row that does not fit
The parse that destructures a row with no check trusts the file. A line without the comma does not match [name, age], and the function stops with a MatchError that prints the line it could not read:
mistake.exs
defmodule People do def parse(line) do [name, age] = String.split(line, ",") {name, String.to_integer(age)} end end People.parse("broken")
elixir mistake.exs
** (MatchError) no match of right hand side value:
["broken"]
mistake.exs:3: People.parse/1
mistake.exs:8: (file)
The fix is the case of the parse function above, which answers a tuple for the shape it did not expect. The rule is the one the errors part of the course keeps returning to: a value from outside the program is checked at the boundary, and a file a person edits is outside the program.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is
String.trim/1the step beforeString.split/2on a line from a file?Answer
because a line ends with its newline
The line mode keeps the terminator, so the last field would carry the newline.
-
What does
Integer.parse/1answer for "36x"?Answer
{36, "x"}
The parse stops at the first character that is not a digit and answers the rest.
-
Why does a parse function answer a tuple instead of raising?
Answer
because a row from a user is outside the program and may not fit
The bad row is an expected failure, so the caller gets a value it can report.
-
What does
Enum.split_with/2answer?Answer
two lists: the items that match and the items that do not
The call partitions the enumerable in one pass and keeps the order of both lists.
-
What does this program print?
IO.inspect(String.split("ada,36", ","))Answer
["ada", "36"]
The split on the comma gives the two fields as a list of strings.
-
What does this program print?
IO.inspect(Integer.parse("36x"))Answer
{36, "x"}
The parse answers the number and the text that was left.
-
What does this program print?
[good, bad] = Enum.split_with([1, 2, 3, 4], &(rem(&1, 2) == 0)) IO.inspect({good, bad})Answer
{[2, 4], [1, 3]}
The function matches the even numbers, which go in the first list.
-
What does this program print?
defmodule P do def parse(line) do [name, age] = String.split(line, ",") {name, String.to_integer(age)} end end IO.inspect(P.parse("ada,36"))Answer
{"ada", 36}
The row fits, and the number is parsed to an integer.
-
What does this program do?
defmodule P do def parse(line) do [name, age] = String.split(line, ",") {name, String.to_integer(age)} end end IO.inspect(P.parse("broken"))Answer
A MatchError, because the split gives one item and the pattern wants two
The pattern of two names does not match a one-item list, and the run stops.
-
Why does a parse function of a whole file use
match?({:ok, _}, result)?Answer
to test the shape without taking the tuple apart
match? asks whether the value fits the pattern and answers a boolean the partition wants.
Article author: Arthur Isaev