Writing a list to file

Is it possible to write a list to a file in Elixir? If yes how can it be implemented?

What list? What is the expected input and output? Do you just want to store Elixir list for loading it later?

No I just want to store a list of tuples to a file, just for the user to be able to read the output a later stage.

list_of_tuples = [{1,2},{3,4}]
bytes = :erlang.term_to_binary(list_of_tuples)
File.write!("data.bin", bytes)

Then later you can:

bytes = File.read!("data.bin")
list_of_tuples = :erlang.binary_to_term(bytes)
2 Likes

But I want to save file as a list of tokens not in byte format.

There is no built-in function that will generate data in such format for you. You need to encode that data on your own.

2 Likes

Well, you said “I just want to store a list of tuples to a file”.

What is your actual use case? What format do you want?

4 Likes

“tokens” is what we programmers see, but in memory or disk, data is represented in binaries. What purpose the list is being used for will result in different representing format, binary or plain.

For example, if you want to save a list of search histories with datetime, you can save it as lines of plain word in a text. You’ll need your own parser / encoder somehow. This could be easy or difficult depending on your data structure.

A binary format in the other hand, provides easy loading & dumping abilities but the mediator is not so friendly for human to read and debug. It’s plainly easy using :erlang.binary_to_term and :erlang.term_to_binary as @benwilson512 demonstrated.

1 Like

So I have a list say :

[ {:"{", 1},
   {:def, 2},
   {:string, 2, 'P'}]

and I want to store them in a file as stated previously .

You’ll need to give an example of what you wish the file to look like when you have saved it.

Text.txt should consists only:

[ {:"{", 1},
  {:def, 2},
  {:string, 2, 'P'}]

You can use inspect to have a string representation… then save it to a file.

An example code:

list = [ {:"{", 1},
  {:def, 2},
  {:string, 2, 'P'}]

content = inspect(list, pretty: true)
File.write!("store.txt", content)
2 Likes

Note, you also want limit: :infinity as an option, otherwise it can be truncated.

3 Likes

One can use IO.inspect/3 which I believe can be optimised for large lists, as will not need to create huge binary.

2 Likes