File.write 收到 :badarg

receiving :badarg on File.write

我开始学习 Elixir,这也是我的第一门动态语言,所以我真的迷失了使用没有类型声明的函数。

我想做什么:
def create_training_data(file_path, indices_path, result_path) do
    file_path
    |> File.stream!
    |> Stream.with_index
    |> filter_data_with_indices(indices_path)
    |> create_output_file(result_path)
  end

  def filter_data_with_indices(raw_data, indices_path) do
    Stream.filter raw_data, fn {_elem, index} ->
      index_match?(index, indices_path)
    end
  end

  defp index_match?(index, indices_path) do
    indices_path
    |> File.stream!
    |> Enum.any? fn elem ->
      (elem
      |> String.replace(~r/\n/, "")
      |> String.to_integer
      |> (&(&1 == index)).())
    end
  end

  defp create_output_file(data, path) do
    File.write(path, data)
  end

当我调用函数时:

create_training_data("./resources/data/usps.csv","./resources/indices/17.csv","./output.txt")

它 returns {:error, :badarg}。我已经检查过,错误出在 create_output_file 函数上。

如果我注释掉函数 create_output_file,我得到的是一个流(有点意思)。问题是我不能给 File.write 一个 Stream 吗?如果有问题,我该怎么办?我在文档中没有找到任何相关内容。

编辑

所以,问题是 File.write 的路径应该没问题,我把函数修改成这样:

defp create_output_file(data, path) do
    IO.puts("You are trying to write to: " <> path)
    File.write(path, data)
end

现在,当我再次尝试使用这些参数 运行 时:

iex(3)> IaBay.DataHandling.create_training_data("/home/lhahn/data/usps.csv", "/home/lhahn/indices/17.csv", "/home/lhahn/output.txt")
You are trying to write to: /home/lhahn/output.txt
{:error, :badarg}
iex(4)> File.write("/home/lhahn/output.txt", "Hello, World")
:ok

所以,我仍然遇到 :badarg 问题,也许我传递的内容不正确?

您写入的目录是否存在?我会试试这个:

defp create_output_file(data, path) do
  File.mkdir_p!(Path.dirname(path))
  File.write!(path, data)
end

第一件事:将 元组 写入 write。您必须先从它们中提取数据:

file_path
|> File.stream!
|> Stream.with_index
|> filter_data_with_indices(indices_path)
|> Stream.map(fn {x,y} -> x end)    # <------------------ here
|> create_output_file(result_path)

第二件事:

您似乎无法将 Stream 馈送到 File。write/2 因为它需要 iodata。如果在写入前将stream转成list,一切顺利:

defp create_output_file(data, path) do
  data = Enum.to_list(data)
  :ok = File.write(path, data)
end