Somebody knows how can I append a new line in the text file in Erlang language? I want to save this list:
Data = ["one", "two", "three"],
into the text file with new lines:
one
two
three
I tried:
write() ->
Data = ["1","2","3"],
Print = string:join(Data, "\n"),
file:write_file("/Documents/foo.txt", [Print]).
But it creates a text file with inline data:
one\ntwo\nthree
I'm guessing you're running your code on Windows, and so you need "\r\n"
as the line separator. You can get the line separator appropriate for the platform you're on by calling io_lib:nl/0
.
Try this instead:
write() ->
Data = ["1","2","3"],
LineSep = io_lib:nl(),
Print = [string:join(Data, LineSep), LineSep],
file:write_file("/Documents/foo.txt", Print).
Here, Print
is an instance of iodata, which is either an iolist
or a binary
, where an iolist
is an arbitrarily deep list consisting of one or more characters, binaries, or other iolists. It's an extremely handy data type for output in Erlang because it means you can avoid having to flatten your data before writing it to a file or sending it over a socket. This version of the write
function uses the iodata
form for the Print
variable to easily ensure that the final line of data written to the file is followed by a line separator, something that string:join/2
by itself won't do.