3 Useful Python Automation Scripts

The post highlights three useful applications of using python to automate simple desktop tasks. Stay tuned till the end of the post to find the reference for a bonus resource.



Whether it's a ten-minute food delivery or ever-so-available content at on-demand services, we all are accustomed to getting things done at our fingertips. The world has always been automating something or the other, be it using simple machines, assembly lines, robots, or computers for processing transactions. Humanity has reaped significant benefits and enjoyed ease by automating and delegating mundane tasks to machines.

 

3 Useful Python Automation Scripts
Photo by olia danilevich

 

When it comes to programming, Python is a much sought-after and easy-to-use language used for automating some of the repeated tasks. As machine learning and AI become mainstream, it is widely getting prominence as it is straightforward to learn. Simple mundane tasks like responding to emails, downloading videos, sending text messages at a particular time of the day to a set of recipients, reading emails out loud, etc can be automated easily with the help of Python.

In this post, we are going to discuss three of the most useful applications of Python and its libraries to automate usual tasks on a desktop.

 

Clean Up Download Folder

 

If you have been using your machine for a while now, there is a high chance you would have a messy Downloads folder. We all have faced such a situation and struggle with manually deleting irrelevant files which are painstakingly difficult – is there a solution? Certainly. Why not automatically delete some of the files, let’s say by type?

Most commonly we end up downloading a lot of pdf files from the internet and thus the script shared below comes in handy to remove such files. Notably, this script removes all the suggested files instead of sending them to the Recycle Bin.

The library which supports this automation is “os”. Start with importing the “os” library. Change your directory to the Downloads directory. Now call the “listdir()” function, which lists all the files and directories inside the current directory i.e. Downloads in our case. Loop through these files, verify if the files end with a “.pdf” extension, and remove the file using the ".remove(file)” method.

import os
os.chdir('/Users/macUser/Downloads')
for file in os.listdir():
    if file.endswith(('.pdf')):
        os.remove(file)

 

You can also add other conditions while filtering out the files of your choice. For example, I generally download images from “web.whatsapp.com” and all these image filenames start with the “Whatsapp” substring.

import os
os.chdir('/Users/macUser/Downloads')
for file in os.listdir():
    if file.startswith(("Whatsapp")) and file.endswith((“.png”, “.jpg”)):
        os.remove(file)

 

The above code deletes all png and jpg files with filenames starting with “Whatsapp”.

 

Automate Your Desktop

 

Now that your Downloads folder is pristinely clean, let’s invite some ghosts to your desktop. Pyautogui is a Python library that supports the automation of mouse pointer movements and keyboard key presses without any hassle.

The below code types the text “This Desktop is Automated!” to the already open TextEdit file. First, import the library “pyautogui” with the alias name “pag”. Call the “doubleClick()” method with the coordinates of where you want to double-click as arguments. In this case, the coordinates are chosen as x = 150 and y = 150.

Please note that on a computer screen the 0,0 coordinates start from the top left corner with the y-axis values increasing as you move down and x-axis values increasing while moving rightwards.

import pyautogui as pag
pag.doubleClick(150, 150)
pag.write('This Desktop is Automated!', interval=0.25)

 

The double-click coordinates lie inside the open text file and thus the cursor blinks inside the file. You can also call a “click()” method instead of a “doubleClick()”. “pyautogui.write()” adds the text where the blinking cursor is located.

The sequence of events looks like the GIF below.

 

3 Useful Python Automation Scripts

 

Pyautogui also lets you move files, save files, select and copy texts, and take screenshots, thus making it a versatile option for desktop automation.

You can also draw some hard-to-draw images like a spiral by reducing the radius of the circle or the length of the side of a square in each iteration. The below code from the official documentation highlights this application.

distance = 200
while distance > 0:
    pyautogui.drag(distance, 0, duration=0.5)   # move right
    distance -= 5
    pyautogui.drag(0, distance, duration=0.5)   # move down
    pyautogui.drag(-distance, 0, duration=0.5)  # move left
    distance -= 5
    pyautogui.drag(0, -distance, duration=0.5)

 

3 Useful Python Automation Scripts
Source: Official Documentation of Pyautogui

 

Downloading YouTube Videos

 

You have a long flight today and need a few YouTube videos to watch on your desktop. It’s easy with “pytube”. Just import pytube, and call the Youtube().streams.first() method with the video URL. Save the output into the video variable and then call the download() method with the location for downloading the video.

Adding exception handling using try and except would help as most of the errors originate from incorrect or incomplete URLs.

import pytube
video_url = 'https://www.youtube.com/watch?v=npA-2ONUqOc'
try:
    video = pytube.YouTube(video_url).streams.first()  
    video.download('/Users/macUser/Downloads')  
    print("Success: The file is downloaded.")
except:
    print("Error: There might be an issue with the url provided.")

 

The output on the console looks like below.

Success: The file is downloaded.

 

You can see the downloaded file in your Downloads folder.

 

3 Useful Python Automation Scripts

 

Bonus Reference

 

The post intends to share a host of tasks that can be automated on a daily basis and make our life easier. As evident from the examples shown in the post, you need not have extensive and advanced knowledge of Python programming to be able to implement such tasks. If you are keen to take it a notch ahead and learn more such examples, then refer to an excellent book “Automate the Boring Stuff with Python: Practical Programming for Total Beginners” by Al Sweigart.  

 

I hope you enjoyed the three applications of Python in automating simple desktop tasks such as cleaning up any folder, downloading youtube videos, and automating the desktop. Your suggestions on automating more tasks using Python are welcome in the comments section below.

 
 
Vidhi Chugh is an AI strategist and a digital transformation leader working at the intersection of product, sciences, and engineering to build scalable machine learning systems. She is an award-winning innovation leader, an author, and an international speaker. She is on a mission to democratize machine learning and break the jargon for everyone to be a part of this transformation.