How to write list into a file

Hi guys,

The following code snippet gives a headache.

 "/home/thiel/testdata.txt"
  |> Path.expand(__DIR__)
  |> File.stream!
  |> Stream.map( &(String.trim(&1, " ")))
  |> CSV.decode
  |> Enum.each( fn({_, y}) -> IO.inspect(y) end)

This code writes the next lists (y) to console:

[“10.5”, “11.5”, “12.5”]
[“20.5”, “21.5”, “22.5”]

How do I have to adapt this code to write the lists to a file?

Many thanks.

Thiel Chang

1 Like

You might use

iex> :erlang.term_to_binary ["10.5", "11.5", "12.5"]
<<131, 108, 0, 0, 0, 3, 109, 0, 0, 0, 4, 49, 48, 46, 53, 109, 0, 0, 0, 4, 49,
  49, 46, 53, 109, 0, 0, 0, 4, 49, 50, 46, 53, 106>>

and the reverse to deserialize… :erlang.binary_to_term

or Poison.encode/decode

iex> Poison.encode ["10.5", "11.5", "12.5"]
{:ok, "[\"10.5\",\"11.5\",\"12.5\"]"}
3 Likes

:erlang.term_to_binary (and the related :erlang.binary_to_term) are able to compress data better (and also able to work with more types of data-structures --like the difference between atoms and strings–) than when performing JSON-encoding/decoding, so that one is preferable, unless you want to be able to read the data inside another environment that does not support the Erlang Binary Format. (Such as when you want your JSON to be searchable in your Postgres database).

3 Likes