Thanks for your response @dimitarvp! I believe managing files using sqlite3 can be very beneficial for particular scenarios. I could create hashes from files and then work with those IDs but my scenarios are quite more mundane. Let me walk through some of them.
Example 1: I regularly dump all my videos and pictures from different sources in a folder. I want to sort them into different folders based on the extension. So I would have a folder for JPG files, another one for PNG files, etc. My files are named IMG_XXXX.jpg. The names roll over each 10.000 pictures, so I have to take care not to overwrite any existing files.
So, in pseudo code it would be something like this:
- List all the files in given directory
- For each file:
a) Check if there is a folder with the same name as the file extension. If it doesn’t exist, create the folder.
b) Check if there is a file with the same name as the current file in the extension directory. If it does exist, rename existing file adding _1 to the end of the name (or _2,_3) to prevent overwrites.
c) Move file to its extension directory.
Reviewing the File doc, my initial take would be to make something like this (Note: this doesn’t work, is pseudo elixir).
defmodule sort_files_by_extension do
def sort_files do
File.ls!("./test")
|> Enum.each(fn filename -> [name | extension] = String.split(filename, ".") end)
|> Enum.each(&check_extension_dir/1)
|> Enum.each(&check_duplicate_files/2)
|> Enum.each(&move_extension_directory/2)
defp check_extension_dir extension do
File.exists?("./#{extension}")
File.dir?("./#{extension}")
# If both checks are false, then create the dir
end
defp check_duplicate_files name, extension do
File.exists?("#{extension}/#{filename}")
# If file exists, append _n to name, checking for duplicates again
end
defp move_to_extension_directory name, extension do
File.rename!("./#{filename}", "./#{extension}/#{name}"
end
end
I’ve been reading Pragmatic Programming book and on the if topic, there is this advice: try to work with functions instead of resorting to classical imperative if/then flows. So right now, I feel I’m a bit handicapped in the middle ground: without too much knowledge about functional and avoiding imperative structures. Any comments or improvements to make this work are kindly welcome!


















