如何获取流并将每行写入文件?
假设我有一个文件文件,我使用File.stream进行流式传输!我对它们进行了一些转换(这里我用替换元素代替元音),但后来我想把它写成一个新的文件。我怎么做?我到目前为止最好的是:
iex(3)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Enum.to_list
["h_ll_", "my", "fr__nd"]
答案 0 :(得分:8)
您需要使用File.stream!
以流模式打开文件,并Stream.into
和Stream.run
将数据写入该文件:
iex(1)> file = File.stream!("a.txt")
%File.Stream{line_or_bytes: :line, modes: [:raw, :read_ahead, :binary],
path: "a.txt", raw: true}
iex(2)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Stream.into(file) |> Stream.run
:ok
iex(3)> File.read!("a.txt")
"h_ll_myfr__nd"
编辑:正如@FredtheMagicWonderDog指出的那样,最好只做|> Enum.into(file)
而不是|> Stream.into(file) |> Stream.run
。
iex(1)> file = File.stream!("a.txt")
%File.Stream{line_or_bytes: :line, modes: [:raw, :read_ahead, :binary],
path: "a.txt", raw: true}
iex(2)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Enum.into(file)
%File.Stream{line_or_bytes: :line, modes: [:raw, :read_ahead, :binary],
path: "a.txt", raw: true}
iex(3)> File.read!("a.txt")
"h_ll_myfr__nd"