Â
 Â
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
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
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.