Elixir writing to files showing as empty

I have the below function. It creates a file in my root directory and when I open that file in VSCode it the content is there as it should be. When I move the file to my desktop and open it in a text editor or Google sheets the file is empty. Not sure what I am doing wrong here:

def write_csv() do
    data = [
      %{
        "age" => "17",
        "name" => "John"
      },
      %{
        "age" => "27",
        "name" => "Steve"
      },
      %{
        "age" => "37",
        "name" => "Meg"
      }
    ]

    file_name = "test_writer.csv"
    headers = ["age", "name"]

    {:ok, file} = File.open(file_name, [:write, :utf8])

    data
    |> CSV.encode(separator: ?,, headers: headers)
    |> Enum.each(&IO.write(file, &1))

    File.close(file)
  end

If you can open the resulting CSV file in VSCode – or with cat on the console – then IMO that’s not an Elixir problem. Still, have you checked file ownership?

Not saying it is an Elixir problem. I’m just curious how I can use Elixir to create a file that I can open and view the contents of for instance if I wanted to create CSV users could download.

I’d suggest using nimble_csv. It has a predefined module, which stores the csv in an encoding most spreadsheet applications can deal with. The generally sane approach of using utf-8 for example doesn’t work in excel.

Thanks, Ill look into nimble_csv