Save elixir print to file

How can I save data generated from the code in a file?

You could use File.write/3

2 Likes

Hello and welcome,

You need the File module, there is a full example here…

TLDR, from linked doc

iex> {:ok, file} = File.open("hello", [:write])
{:ok, #PID<0.47.0>}
iex> IO.binwrite(file, "world")
:ok
iex> File.close(file)
:ok
iex> File.read("hello")
{:ok, "world"}

Replace “world” by your generated data.

2 Likes

Hi!
suppose this is my code:

defmodule GenerateRandom do
  def random_a(length, list \\ [])
  def random_a(0, list), do: list
  def random_a(length, list) do
    length - 1
    |> random_a([random_number() | list])
  end
  defp random_number() do
    :rand.uniform() * 100
    |>Float.round(8)
  end
end

I want to add in the file all the numbers that are generated then ¿how would I do it?

You are using length like a loop index…

It’s not a common pattern in FP.

Maybe something like this?

iex(1)> random_a = fn length -> Enum.map(0..length, fn _x -> Float.round(:rand.uniform() * 100, 8) end) end
#Function<7.91303403/1 in :erl_eval.expr/5>
iex(2)> {:ok, file} = File.open("hello", [:write])
{:ok, #PID<0.111.0>}
iex(3)> random_a.(5) |> Enum.map(fn n -> IO.write(file, "#{n}\n") end)     
[:ok, :ok, :ok, :ok, :ok, :ok]
iex(4)> File.close(file)
:ok
iex(5)> File.read("hello")
{:ok,
 "25.62941465\n99.32284817\n24.45550849\n47.37121892\n52.10289673\n54.59559738\n"}
2 Likes