Introduction
In today's rapidly evolving world, where time holds a value even greater than money, allocating it to mundane and repetitive tasks can seem not only boring but also robs us of opportunities for growth and creativity. However, with the advent of the internet and new technologies like Python programming, one can manage their tasks and regain control over their valuable time. In today's blog post, we will delve into the world of Python automation and also build a file manager automation script, that not only monitors a specific directory but also intelligently organises incoming files into their appropriate folders, from scratch.
Why Python Automation?
Before we dive into the technical intricacies of building the tool, let us first understand the concept of automation and the distinct advantages Python brings over other numerous other programming available. In simple terms, automation is a way to assign a routine task to a program or a script, thus allowing you to focus on other important jobs. Now, Python as a programming language contains an extremely easy and user-friendly syntax with an abundant amount of libraries that can be used by individuals regardless of their coding experience to streamline their workflows. From managing files and sending emails to reading .csv files and manipulating data, python's versatility makes it an ideal choice for an automation project.
Building a File Manager Automation Script
Step 1: Setting up an Environment
To begin, let's ensure that Python is installed in our system. You can download it from the official Python website. Additionally, you might also need an IDE which stands for Integrated Development Environment, it is a tool that you will use to write and execute your code. You can go for IDEs such as VisualStudio Code, PyCharm or Jupyter Notebook as they contain a clean UI and is extremely easy to use.
Step 2: Importing required libraries
Now that we have installed Python and the IDE of your choice, let us start writing our code. For this project, we will need to import libraries such as os
for managing directories, shutil
for moving files from one directory to another, time
for representing time in code, logging
for emitting log messages and watchdog
for monitoring a particular directory.
import os
import time
import logging
import shutil
os
and shutil
are built-in library so you can directly use it, but you will need to install watchdog
into your system.
To do so, open your terminal and install watchdog
. You can install it using pip.
pip install watchdog
Now import it into your code.
from watchdog.observers import Observers
from watchdog.events import FileSystemEventHandle
Step 3: Defining the functions
Now, that all the libraries have been imported into our code let us write the code that monitors the incoming files and performs the necessary operations.
First, we need to store the path of the directory in a variable.
source_directory = "/path/to/source/directory"
dest_directory = "/path/to/destination/directory"
We can create a list containing all the extensions that can be used to identify the class of file it may belong to, eg. For an image, the list shall look like the following:
image_extensions = [".jpg", ".jpeg", ".jpe", ".jif", ".jfif", ".jfi",
".png", ".gif", ".webp", ".tiff", ".tif", ".psd", ".raw", ".arw",
".cr2", ".nrw", ".avif",".k25", ".bmp", ".dib", ".heif", ".heic",
".ind", ".indd", ".indt", ".jp2", ".j2k", ".jpf", ".jpf", ".jpx",
".jpm", ".mj2", ".svg", ".svgz", ".ai", ".eps", ".ico"]
Here, organise_files() is the class we will be using to scan the source_directory and decide the type of file that resides in it.
class organise_files(FileSystemEventHandler):
def on_created(self, event):
with os.scandir(source_path) as items:
for item in items:
name = item.name
name = name.lower()
self.check_images(name)
def check_images(self, name):
for file in image_extensions:
if name.endswith(file):
check_folder(dest_directory, name)
logging.info(f"Moved image file: {name}")
The above code block is for checking if the file belongs to the image category or not. After checking we shall first check if the dest_directory exists and then move the files.
def move_files(source, dest):
shutil.move(source, dest)
def check_folder(dest, name):
if os.path.exists(dest):
move_files(os.path.join(source_path, name),dest )
else:
os.mkdir(dest)
move_files(os.path.join(source_path, name),dest)
Step 4: Putting it all together
Now, we shall use the watchdog function to monitor this directory and call the organise_files
class when there is a new file added to the directory.
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = source_directory
event_handler = organise_files()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
Conclusion
With our file manager automation script in place, the days of manually sorting files into folders are over. This project exemplifies how Python automation can significantly enhance your productivity by handling mundane tasks, allowing you to channel your energy into more meaningful endeavours. Whether you're a student, a professional, or simply someone looking to make the most of your time, Python automation is a valuable tool in your arsenal.
Incorporating automation into your routine not only saves time but also empowers you to think creatively, solve complex problems, and achieve your goals. As you embark on your journey into the world of Python automation, remember that the possibilities are endless, and your newfound time is yours to reclaim and reinvest in pursuits that truly matter.