Automate organizing file using Python
To automate organizing files in python firstly we have to import the required modules which are os and shutil then we have to assign the directories we’ll be working to appropriate variables and then make categories of files with the help of tuples such as docs, images and software. after that we have to make a list of all files present in root directory(In our case root directory is Downloads folder) using for loop and methods provided in os module. Lastly we have to move all the files present in downloads folder into their respective folders using move function of shutil module.
Before running the code we’ll need to create 5 folders in the downloads folder: images, documents, software, others, and a Log folder that will store the Log.txt file generated by our Python program. After running the program, we can see that there is nothing but 5 folders that we created in the downloads folder, and inside these 5 folders are the respective files.
NOTE: Before running the script, change the directory to Downloads by typing cd Downloads in the terminal.
Code:
Python3
# importing required modules import os from shutil import move # making the directories root_dir = "C:\\Users\\[Username]\\Downloads" image_dir = "C:\\Users\\[Username]\\Downloads\\images" documents_dir = "C:\\Users\\[Username]\\Downloads\\documents" others_dir = "C:\\Users\\[Username]\\Downloads\\others" software_dir = "C:\\Users\\[Username]\\Downloads\\softwares" # files types of each category docs = ( '.docx' , '.doc' , '.txt' , '.pdf' , '.xls' , '.ppt' , '.xlsx' , '.pptx' ) images = ( '.jpg' , '.jpeg' , '.png' , '.svg' , '.tif' , '.tiff' , '.gif' ,) softwares = ( '.exe' , '.dmg' , '.pkg' ) # appending all the files in the root directory to files[] files = [] for f in os.listdir(root_dir): if os.path.isfile(f) and not f.startswith( '.' ) and not f.__eq__(__file__): files.append(f) # moving files to the respective folders, # overwriting if needed for file in files: if file .endswith(docs): move( file , documents_dir + "/" + file ) elif file .endswith(images): move( file , image_dir + "/" + file ) elif file .endswith(softwares): move( file , software_dir + "/" + file ) else : move( file , others_dir + "/" + file ) |
Output:
Automate Renaming and Organizing Files with Python
In this article, we are going to know how to automate renaming and organizing files with Python, hence, the article is divided into two sections: one teaches us how to organize files and the latter how to rename files.