defmodule Sales do def csv_to_list(filename) do {:ok, file} = File.open(filename, [:read]) headers = (IO.read(file, :line) |> parse_csv_atom) IO.stream(file, :line) |> Enum.map(fn l -> parse_csv(l) end) |> Enum.map(fn sales -> Enum.zip(headers, sales) end) end defp parse_csv_atom(line) do String.trim(line, "\n") |> String.split(",") |> Enum.map(&String.to_atom/1) end defp parse_csv(line) do [id, ship_to, net_amount] = (String.trim(line, "\n") |> String.split(",")) [String.to_integer(id), String.to_atom(String.trim(ship_to, ":")), String.to_float(net_amount)] end end IO.inspect Sales.csv_to_list("sales.csv")
^o^ > cat sales.csv id,ship_to,net_amount 123,:NC,100.00 124,:OK,35.50 125,:TX,24.00 126,:TX,44.80 127,:NC,25.00 128,:MA,10.00 129,:CA,102.00 130,:NC,50.00 ^o^ > elixir practice_11_7.exs [[id: 123, ship_to: :NC, net_amount: 100.0], [id: 124, ship_to: :OK, net_amount: 35.5], [id: 125, ship_to: :TX, net_amount: 24.0], [id: 126, ship_to: :TX, net_amount: 44.8], [id: 127, ship_to: :NC, net_amount: 25.0], [id: 128, ship_to: :MA, net_amount: 10.0], [id: 129, ship_to: :CA, net_amount: 102.0], [id: 130, ship_to: :NC, net_amount: 50.0]]