I have a modified version of this really cool script that was written the better half of a decade ago to reorganize really large folders full of random files into their respective directories. My modifications are irrelevant to the question, so I'll use the original script in my example below.
I've set it to prompt for user input instead of hardcoding variables into the script (shown below in between the MY CURRENT EDITS
comments) and that seems to work well enough, but I am worried that it might end up accidentally eating an entire directory I don't intend it to work on, if I make a mistake.
Questions:
Is there a means by which I can make it prompt the user for the reorg_dir
in such a way it lets a user scroll through directories, select a directory, and then double check to make sure the user is happy with what will happen?
In the same vein, is there a means by which one could be prompted to exclude some filetype, else it excludes nothing?
Continuing, how about remove_emptyfolders
, else assume True
?
(Question 1 is the most important one. I don't expect you to solve the whole problem for the rest of'em if you aren't feeling ambitious!)
#!/usr/bin/env python3
import os
import subprocess
import shutil
# ---------------------------------------------
reorg_dir = "/path/to/directory_to_reorganize"
exclude = (".jpg") # for example
remove_emptyfolders = True
# ---------------------------------------------
# MY CURRENT EDITS ---------------------------------------
while True:
dirReorg= input("What directory do you want to organize by filetype?")
if not os.path.exists(dirReorg):
print("That path doesn't exist. Try again!")
continue
break
reorg_dir = os.path.abspath(dirReorg)
# end MY CURRENT EDITS -----------------------------------
for root, dirs, files in os.walk(reorg_dir):
for name in files:
subject = root+"/"+name
if name.startswith("."):
extension = ".hidden_files"
elif not "." in name:
extension = ".without_extension"
else:
extension = name[name.rfind("."):]
if not extension in exclude:
new_dir = reorg_dir+"/"+extension[1:]
if not os.path.exists(new_dir):
os.mkdir(new_dir)
shutil.move(subject, new_dir+"/"+name)
def cleanup():
filelist = []
for root, dirs, files in os.walk(reorg_dir):
for name in files:
filelist.append(root+"/"+name)
directories = [item[0] for item in os.walk(reorg_dir)]
for dr in directories:
matches = [item for item in filelist if dr in item]
if len(matches) == 0:
try:
shutil.rmtree(dr)
except FileNotFoundError:
pass
if remove_emptyfolders == True:
cleanup()