…where the name is made up of the date and time.
I’ve got a lot of image files that I tend to dump into whatever directory I feel like.
This simple python script will create directories and move files around based on the file name, as long as the filename follows the following format YYYYMM
Notice I’m not checking for JPG/MP4 files only; I’m not checking that the year or month are valid values; I’m not checking the EXIF values and basing it on them if the filename is not valid; there are lots of really cool things I could do as well but I don’t need those because that’s how my files are set out. I’m not building in lots of features that don’t touch my use-case.
import os import shutil path = '/home/mike/TestPython/' os.chdir(path) for file in os.walk(path): for name in file[2]: year = name[:4] month = name[4:6] if name[:6].isdigit(): if not os.path.exists(year): os.makedirs(year) if not os.path.exists(year + "/" + month): os.makedirs(year + "/" + month) src = file[0] + "/" + name dst = path + year + "/" + month + "/"+name shutil.move(src, dst)
Once you’ve moved all the files into their new homes delete all the empty directories. This code has been ever so slightly modifed from this StakOverflow post. It was modified for Python 3, by adding brackets to the print syntax:
import os currentDir = '/home/mike/TestPython/' index = 0 for root, dirs, files in os.walk(currentDir): for dir in dirs: newDir = os.path.join(root, dir) index += 1 print (str(index) + " ---> " + newDir) try: os.removedirs(newDir) print("Directory empty! Deleting...") print(" ") except: print("Directory not empty and will not be removed") print(" ")