Home Posts Tags Post Search Tag Search

Post 7

Elixir read/write files

Published on: 2025-04-01 Tags: elixir, NimbleParsec, Libraries, files, stream
File is a function that can do what you need for any given read/write. I made these 2 functions for accessing and writing to a file.

def open_file(file_path \\ "camel_case_test_lines.txt") do
    case File.read(file_path) do
      {:ok, content} ->
        String.split(content, "\n", trim: true)

      {:error, reason} ->
        {:error, "Failed to open file: #{reason}"}
    end
  end

  def write_file(lines, target_file \\ "camel_case_test_lines.edit") do
    case File.open(target_file, [:write, :utf8]) do
      {:ok, target} ->
        Enum.each(lines, fn line -> IO.write(target, line) end)

        File.close(target)
        IO.puts("Successfully wrote to #{target_file}")

      {:error, reason} ->
        {:error, "Failed to open target file: #{reason}"}
    end
  end

open_file/1 is just used for opening a file and putting every line into a list.
write_file/2 is used for writing to a file.

in this case you could simply pass the same file to each one and it would just output the exact same thing.

There is also the stream/1 that can do the same as the File.open()

def open_file(file_path \\ "camel_case_test_lines.txt") do
  File.stream!(file_path) |> Enum.to_list()
end