Organise Files Using Python in 5 Minutes
by LethargicPerson in Teachers > 9
89 Views, 1 Favorites, 0 Comments
Organise Files Using Python in 5 Minutes
No one likes to see messy files in their downloads folder. In this instructable, I will show you how to organise your files in 5 minutes.
At the end your messy folder will get organised in folders of files with their extension categories.
Supplies
What do you need?
- A computer (Laptop)
- Python
What will you learn?
- Using os library in Python
Note: If you do not already have Python installed, do not worry I will show you how to install it in the next step.
Installing Python
Just go to the following link and download the 3.8 or 3.9 version of Python as in the picture.
After it is downloaded, open it up and choose the "Install Now" button. After this, everything is next-next click process. After it is installed, it will say setup successful as in the picture.
Choosing Our Folder and Coding.
Here, we have to choose which folder we want to organize with our script. Lets choose the downloads folder since that is messy for most people. I have included a picture of my downloads folder. Notice how messy it is.
Now you need to copy its path.
Next, open up IDLE which comes installed with Python. Click File>New File. Now copy the following code and paste it in the idle window that opens up.
import os downloads_dir = "C:\\Users\\Ashutosh\\Downloads" all_files = os.listdir(downloads_dir) all_fext = [] #split all file extensions from the dir for f in all_files: _, fext = os.path.splitext(f) if fext not in all_fext: all_fext.append(fext) #create all dirs to organise files for ext in all_fext: if ext: os.mkdir(os.path.join(downloads_dir, ext)) #move all files to their respective dirs for f in all_files: _, ext = os.path.splitext(f) old_path = os.path.join(downloads_dir, f) new_path = os.path.join(downloads_dir, ext, f) os.rename(old_path, new_path)
Don't forget to replace PATH variable with the path of the folder you are organizing.
Note: Do not forget to use double slashes for path or python will throw you can error.
Save the file by Ctrl+S in any other folder than the one you are going to organize as organise.py.
I have included a python file in this step below for reference.
Downloads
Running the Script.
The last step is to run the file and watch it work.
In order to run the file just do "F5" or you can click Run>Run Module. After doing this, another IDLE window will open up which will look like in the picture after you script is finished running.
Now just rush to your folder which you aimed to organize, and you will notice that it has been organized into folders with names like .exe, .pdf. etc. Something like in the picture.
I have made a video tutorial for this.
Note: Either follow the instructable or the video tutorial, don't follow both.