2016-08-29 26 views
1

如何獲取流並將每行寫入文件?如何流入Elixir的文件?

說我有使用File.stream!流的單詞文件,我對它們進行了一些轉換(在這裏我用下劃線替換元音),但是接下來我想將其寫入一個新文件。我怎麼做?最好的我已經走到這一步,是這樣的:

iex(3)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Enum.to_list 
["h_ll_", "my", "fr__nd"] 

回答

4

您需要使用File.stream!打開流模式文件,並Stream.intoStream.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" 
+1

我想你可以只用'Enum.into'以及而非'Stream.into |> Stream.run' –

+0

如果該文件不存在發生? 如果文件不存在,您可以在寫入時創建嗎? – Asincrono

+0

你是否仍然想使用'Stream.into |> Stream.run'?由於'Enum'函數是渴望的,'Stream'函數是懶惰的。 –

相關問題