Organize Your Files Like a Pro with Python: Step-by-Step Instructions
Python has consistently ranked as one of the top 3 programming languages in recent years. In this brief article, I will teach you how you can use Python to organise files on your computer based on file extensions.
First of all, you should have Python installed on your system. If you don't, kindly refer to my article, "Installing Python on Your System: A Step-by-Step Guide".
Open your code editor (I like to use VSCode) and type the following:
#importing os and shutil modules
import os, shutil
os and shutil are both known as modules in Python. A module is simply a file with the .py extension that can be imported inside another Python program. The os module provides a portable way of using operating system-dependent functionality whereas the shutil module offers several high-level operations on files and collections of files.
Save the file to your desktop and name it sorting.py
. Update your code with the following snippet:
#Defining the source directory. Replace 'User' with your computer's user
source_directory = 'C:\\Users\\User\\Downloads'
#os.listdir is used to get the list of all files and directories
files = os.listdir(source_dir)
print(files)
Open your Command Prompt (cmd) and navigate to the folder where your Python file was saved. In this example, I will navigate to the desktop and run the Python script.
> python sorting.py
You should see something similar to the screenshot below, a list of all files and folders in the source directory.
Return to your code editor and update your code with the following:
for file in files:
if os.path.join(source_directory, file).endswith(('.txt', '.pdf', '.docx')):
shutil.move(os.path.join(source_dir, file), os.path.join(source_directory, "Documents"))
if os.path.join(source_dir, f).endswith(('.png', '.jpg')):
shutil.move(os.path.join(source_dir, f), os.path.join(source_dir, "Photos"))
The code above loops through all files in the source directory and moves them to the Documents
folder if the filename ends with.txt
.pdf
, or .docx
. It also moves all files with a .png
or .jpg
extension into the Photos
folder. After you update your code, re-run the python sorting.py
command in your command prompt.
Note that both the
Documents
andPhotos
folders should be created in the downloads folder before running your script.
Conclusion
Hopefully, I have been able to help you organise your files more efficiently. Feel free to drop your questions and suggestions in the comments section.
Subscribe to my newsletter
Read articles from George Addai directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
George Addai
George Addai
I am a tech lover and a developer who is interested in Python and the Django framework. I love to build things using code.