I have some files with different extensions such as *.pdf
, *.mp3
, *.jpg
and a few others. All of them are stored in a parent
directory.
How can I get a list of all extensions, create some folders based on these extensions and then move all files into their relevant folders?
The python script below does the job. Hidden files are stored separately in a folder , as well as files without extension.
Since it might be used for a wider range of purposes, I added a few options:
exclude = ()
remove_emptyfolders = True
orFalse
)by:
The script:
IF there is a risk of unwanted overwriting duplicate files
At the expense of a few extra lines, we can prevent overwriting possible duplicates. With the code below, duplicates will be renamed as:
etc.
The script:
EDIT
With OP in mind, we all forgot to add an instruction on how to use. Since duplicate questions might (and do) appear, it might be useful nevertheless.
How to use
reorganize.py
In the head section of the script, set the targeted directory (with the files to reorganize):
(use quotes if the directory contains spaces)
possible extensions you'd like to exclude (probably none, like below):
and if you'd like to remove empty folders afterwards:
Run the script with the command:
NB if you'd like to copy the files instead of move, replace:
by:
Please try first on a small sample.
You can use
find
with a somewhat complexexec
command:Replace
cp
withecho
for a dry run.More efficient and tidier would be to save the
bash
command in a script (say, at/path/to/the/script.sh
):And then run
find
:This approach is pretty flexible. For example, to use the filename instead of the extension (
filename.ext
), we'd use this forEXT
:Calculating the list of extensions (after moving):
Calculating the list of extensions (before moving):
(in this last exemple, we are calculating the number of files for each extension and sorting it)
Try this shell script.
If you have Perl's rename/prename installed: