Organize your files with Python
Are you tired of the cluttered and disorganized state of your computer? Do you want to get rid of the chaos of scattered files and bring some order to your digital life? One solution is to purchase AI Fastest Cinderella Cleaner 2023 Ultra Max, using the promo code … 😉
Alternatively, you can take matters into your own hands and create a Python script to help clean up your computer. In this tutorial, we will be learning how to write our own Python script to achieve this goal.
I tried to simplify on Einstein’s advice as much as possible, but not more. That’s why in this script, we use just three modules to accomplish the task of sorting files by extension: pathlib for working with file paths, schedule for setting up a cleaning schedule, and timefor executing the schedule. While it is possible to achieve the same effect with little more lines of code by using the os module or combining os and pathlib I have chosen to use pathlib here for its simplicity and readability.
Introduction
Before diving into the script, it’s important to understand the following concepts:
- How do we want to sort our files? And how do we code it?
- How do we get the path to the folder we want to clean up?
- How do we iterate over the files in the directory?
- How do we check if a file’s extension is in our list of extensions to sort by?
- How do we move a file to a folder based on its extension?
- How do we set up a cleaning schedule and execute it at the desired intervals?
- How do we run the script on startup and keep it running in the background?
By answering these questions, we can fully understand the script and customize it to meet our specific needs.
1. File types and file extensions
We can classify files into several categories, including “images,” “audio,” “video,” “documents,” and “scripts”. Once we have divided our files into categories, we need to assign specific file extensions to each group. The choice of using a dictionary, list, or tuple to write our program does not significantly affect the smooth operation of our code.
file_type = (
('Images', 'jpg, png, gif'),
('Audio', 'mp3, wav, flac'),
('Videos', 'mp4, avi, mkv, webm'),
...)
# or
file_type = {
'IMAGES': 'jpg, png, gif',
'AUDIO': 'mp3, wav, flac',
'VIDEOS': 'mp4, avi, mkv, webm'
...}
# or
file_type = {
'IMAGES': ['jpg', 'png', 'gif'],
'AUDIO': ['mp3', 'wav', 'flac'],
'VIDEOS': ['mp4', 'avi', 'mkv', 'webm'],
...}
#or
file_type = {
'jpg': 'Images',
'png': 'Images',
'gif': 'Images',
'mp3': 'Audio',
'wav': 'Audio',
'mp4': 'Videos',
'avi': 'Videos',
'webm': 'Videos',
'pdf': 'Documents'
...}My sample list will look like this:
file_type = {
'IMAGES': 'jpg, png, gif, jpeg',
'AUDIO': 'mp3, wav, flac',
'VIDEOS': 'mp4, avi, mkv, webm',
'SHEETS': 'xls, xlsx, gsheet',
'DOCS': 'doc, docx, gdoc',
'BOOKS': 'pdf, epub, mobi',
'ARCHIVES': 'zip, tar, rar',
'DATABASES': 'db, sql, csv, json',
'OTHER_DOCS': 'txt, md, ppt, pptx',
'PYTHON': 'py, pyw, ipynb',
'JAVASCRIPT': 'js',
'HTML': 'html, htm',
}2. Path
In this tutorial, we will be using the Path module from the pathliblibrary to manipulate file paths in a more convenient and flexible way. With the Path module, we can easily build, parse, and manipulate file paths without having to manually join strings or worry about operating system-specific syntax. For example, instead of hardcoding a file path like D:\my_file, we can use the Path module to create a path object that represents the same location. This can make our code more portable and easier to maintain, as we don’t have to worry about the specific syntax or formatting of file paths on different operating systems.
Get Data Believer’s stories in your inbox
Join Medium for free to get updates from this writer.
In this example, we will be organizing the Downloads folder, which is a common location on many computers where files downloaded from the internet are stored. To access the path to this folder on a Windows computer, we have two options. One option is to manually build the file path using the username of the current user and the fixed path to the Downloads folder, which is typically located at C:\Users\%username%\Downloads.Alternatively, we can use the Pathmodule from the pathlib library to more conveniently and flexibly manage the file path. This can be particularly useful if we need to access the Downloads folder for multiple users or on different computers with different usernames, as we can use the Path module to automatically construct the correct file path without having to hardcode the username.
path = Path(f'{str(Path.home())}\Downloads')To make it easy to change the file path when calling the organize_filesfunction, we can use a combination of the Path module from the pathlib library and string formatting to build the path dynamically.
3. Iterates
for file in path.iterdir():
if file.is_file():
...The iterdir() method of the Path class returns a generator object that allows us to iterate over all of the files and directories within a given directory. The example iterdir() looks like this:
<path.iterdir generator object at 0x00000274DEE712E0>.The is_file() function, as its name suggests, checks if the object returned by iterdir() is a file.
4. Check a file’s extension
for file in path.iterdir():
if file.is_file():
file_ext = file.suffix[1:]
for key, value in file_type.items():
if file_ext in value:
move(key)
break
else:
move('OTHERS')This code iterates through all of the files in the specified directory and performs the following actions:
If the current file is a regular file (i.e., not a directory or special file), it extracts the file extension from the file name using the suffixattribute and removes the leading period.
It then iterates through the key-value pairs in the file_type dictionary. For each pair, it checks if the file extension of the current file is included in the list of extensions associated with the key.
If the file extension is found in the list of extensions, the code calls the move function and passes the key as an argument. This will move the file to the appropriate directory based on its file type.
If the file extension is not found in any of the lists of extensions, the code calls the movefunction and passes the string OTHERS as an argument. This will move the file to a catch-all OTHERS directory for files that do not match any of the other categories.
5. Move files
def move(folder):
folder_path = path / folder
if not folder_path.exists():
folder_path.mkdir()
file.rename(folder_path / file.name)The function starts by creating a variable called folder_pathwhich is the concatenation of a directory path and the folder passed in as a parameter. In this scenario, the selected folder will be either one of the folders listed in the file_type dictionary or the OTHERSfolder.
Then, it checks if the folder path represented by the folder_path variable does not exist. If this condition is met, it creates a new directory at that location by calling mkdir()method on folder_path.
After this, the code is renaming the file by taking the file name and move it to the folder_path by joining them.
6. Schedule
The schedule library is a python library that allows you to schedule tasks to be executed at specified intervals. It is a lightweight and simple library that is easy to use and understand.
Library schedulegives us many opportunities:
schedule.every(10).seconds.do(job)
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)while True:
schedule.run_pending()
time.sleep(1)For further information, refer to the documentation available at https://schedule.readthedocs.io/en/stable/
7. Startup
How to add a Python script to the autostart I explained this in an earlier YouTube video:
Code
import schedule
import time
from pathlib import Path
file_type = {
'IMAGES': 'jpg, png, gif, jpeg',
'AUDIO': 'mp3, wav, flac',
'VIDEOS': 'mp4, avi, mkv, webm',
'SHEETS': 'xls, xlsx, gsheet',
'DOCS': 'doc, docx, gdoc',
'BOOKS': 'pdf, epub, mobi',
'ARCHIVES': 'zip, tar, rar',
'DATABASES': 'db, sql, csv, json',
'OTHER_DOCS': 'txt, md, ppt, pptx',
'PYTHON': 'py, pyw, ipynb',
'JAVASCRIPT': 'js',
'HTML': 'html, htm',
}
def organize_files(directory):
path = Path(f'{str(Path.home())}\{directory}')
def move(folder):
folder_path = path / folder
if not folder_path.exists():
folder_path.mkdir()
file.rename(folder_path / file.name)
for file in path.iterdir():
if file.is_file():
file_ext = file.suffix[1:]
for key, value in file_type.items():
if file_ext in value:
move(key)
break
else:
move('OTHERS')
schedule.every(15).minutes.do(organize_files, 'Downloads')
while True:
schedule.run_pending()
time.sleep(1)Summary
The purpose of the tutorial is to showcase the capabilities of the Python programming language and how it can be applied beyond just commercial uses. It aims to demonstrate that Python can be a valuable tool for streamlining and automating everyday personal tasks. The script provided in the tutorial has been simplified as much as possible to make it easy for even those who are new to Python to understand. The tutorial encourages readers to take the script and improve upon it by adding more features and functionality, such as dealing with duplicates, to better suit their needs. This is a great way to learn and gain experience with the language while also making their daily tasks more efficient.









