Python script to bring all files from subfolders to main folder
A usual plight with me is bringing all photos I transfer from my phone to one folder. My phone transfer creates a subfolder for each date it has a pic for.
This was till I discovered the module shutil. (No, I knew about it for around _4 months, but I was too lazy to actually write the code 😛 )
This code I have written is meant to be cross-platform. In case of any discrepancies, please do tell.
import shutil import os # copy all the files in the subfolders to main folder # The current working directory dest_dir = os.getcwd() # The generator that walks over the folder tree walker = os.walk(dest_dir) # the first walk would be the same main directory # which if processed, is # redundant # and raises shutil.Error # as the file already exists rem_dirs = walker.next() for data in walker: for files in data: try: shutil.move(data + os.sep + files, dest_dir) except shutil.Error: # still to be on the safe side continue # clearing the directories # from whom we have just removed the files for dirs in rem_dirs: shutil.rmtree(dest_dir + os.sep + dirs)
Since the code is all documented, I would skip the explanation here.
Please comment, share or like the post. (Good for my writing spirit 🙂 )