DEV Community

Cover image for Basic [File Manipulation] With Elixir
Anthony Gonzalez
Anthony Gonzalez

Posted on β€’ Edited on β€’ Originally published at elixirprogrammer.com

3 1

Basic [File Manipulation] With Elixir

 
 

 
 

Learn how to do basic directories and files creation, open, read, write to files with Elixir.

Step 1:

Let's create a new Elixir project by going to the command line and typing the following in your desired directory:

$ mix new file_manipulator && cd file_manipulator

Step 2:

Open your test file test/file_manipulator_test.exs, remove the autogenerated test and add the following test:

  setup do
    file = %{
      name: "test.exs",
      directory: "my_test",
      content: "IO.puts ",
      content_to_append: "\"Hello world from Elixir\""
    }

    %{my_file: file}
  end

  test "creates file", %{my_file: file} do
    my_file = FileManipulator.create(file)

    File.rm_rf!(file.directory)

    assert my_file == {:ok, :ok}
  end

  test "error when files exists", %{my_file: file} do
    FileManipulator.create(file)

    assert FileManipulator.create(file) == {:error, :eexist}

    File.rm_rf!(file.directory)
  end
Enter fullscreen mode Exit fullscreen mode

Go to the command line and run the test mix test and see it fail.

Step 3:

Let's make our test pass by opening our main project file lib/file_manipulator.ex, remove the autogenerated hello world function and add the following:

  def create(file) do
    with :ok <- File.mkdir(file.directory),
         :ok <- File.write("#{file.directory}/#{file.name}", file.content)
    do
      append_to_file(file)
    else
      error ->
        error
    end
  end

  def append_to_file(my_file) do
    File.open("#{my_file.directory}/#{my_file.name}", [:read, :write], fn file ->
      IO.read(file, :line)
      IO.binwrite(file, my_file.content_to_append)
    end)
  end
Enter fullscreen mode Exit fullscreen mode

Get back to the command line and run the test mix test now our test should pass with no failures.

Code Breakdown

File.mkdir(path)

Makes the directory path if it doesn't exist, returns :ok if successful.

File.write(path, content)

Writes Content to the file path, creates the file if it doesn't exist, returns :ok if successful.

File.open(path, modes, function)

Opens the file in reading and writing mode.

IO.read(file, content)

Reads the content of the file, if you don't it gets overridden by the write function.

IO.binwrite(file, content)

Appends the content to the file.

Conclusion

That's a simple introduction to file manipulation with Elixir, all you need is the File, and the input-output IO modules. Thank
you so much for your time, I really appreciate it.

 
 

Join The Elixir Army

Image of Timescale

πŸ“Š Benchmarking Databases for Real-Time Analytics Applications

Benchmarking Timescale, Clickhouse, Postgres, MySQL, MongoDB, and DuckDB for real-time analytics. Introducing RTABench πŸš€

Read full post β†’

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay