Some days ago, I remembered an old problem I had wanted to solve for a long time: monitoring a directory and automatically renaming its contents. Possible use cases are downloads folders, if you want to avoid whitespaces in your filenames or shared folders if you want to educate your collaborators to follow certain rules in giving filenames.
Over the last months I had always procrastinated on implementing this - like too many other things. Fast forward to yesterday, I did some quick checks for tools with the same functionality. If possible, I needed them independent of platforms as I am still switching back and forth between Linux and Windows.
I could only find this tool. Unfortunately, it seems to be Windows exclusive, and, let's face it, running a process 24/7 in Wine is just not that great. Worse yet the download link seemed to be broken at the time. It is now working, so it might have just been a temporary problem, but waiting would have taken longer than doing a basic implementation of what I wanted myself. The same goes for any deeper research.
Below you can find the code for it, written in Python 3. It checks the directory it is in every 15 seconds, replaces whitespaces (and everything added in the list toescape) with hyphens, and deletes everything in the list todel. Of course, this is very limited, but it is a start. Also, please excuse the non-working formating below. I hope anyone to potentially use this can add the tabstops themselves (posting code is unfortunately still a major hassle with my CMS).
import os, time
def renamer_folder(such):
# Scanning the folder
liste = os.listdir(such)
for i in liste:
if os.path.isfile(such + "/" + i) == False:
print ("-- Opening new directory: " + such + "/" + i + " --")
renamer_folder(such + "/" + i)
else:
# Finalname is initially set to be the original filename and then edited to meet the wanted result
finalname = i
# Set up lists with values to be escaped or deleted
toescape = [' ', '%20']
todel = []
for j in todel:
finalname = finalname.replace(j, '')
for j in toescape:
finalname = finalname.replace(j, '-')
finalname = finalname.strip('-')
if finalname != i:
os.rename(such + "/" + i, such + "/" + finalname)
print (" ---- Renaming: " + such + "/" + i + " into " + such + "/" + finalname + " ---- ")
else:
pass
print
("-------------------")
if __name__ == "__main__":
# As the function is meant to be run endlessly, a while loop with conditions that are always true is set
while 1 != 0:
renamer_folder('.')
# Until the script is terminated, it will monitor the directory and its subdirectories recursively every 15 seconds
time.sleep(15)