Top 10 python scripts for automation to boost productivity

Top 10 python scripts for automation to boost productivity

Dhaval Baldha

18 Nov 2023

15 MINUTES READ

Introduction

Since the website has been a basic necessity for every organisation various frameworks and programming languages were introduced allowing developers to build a robust and user-friendly website for every user.

From the coding language of PHP to Ruby on Rails frameworks are being used to create the best website that supports and allows their business to expand.

As every framework has different purposes and outcomes according to the company requirements, the ultimate result is the website for which every developer is heading towards a high-programing language such as Python development.

What is python?

Python can be defined as a high-level and a general purpose programming language with a simple syntax quite similar to the English language making it easier to understand. With the help of Python, the developers can create websites and software in fewer coding lines compared to other programming languages making it the best option for automation tasks.

Why python for automation?

It’s not just the easy syntax and few coding lines but data structure also matters when it comes to automation. It allows you to store data and acquire it with the help of data structure which can be viewed in various forms list, set or even in a dictionary format.

Moreover, with the help of its flexibility, you can even customise your data structure at your convenience. As it's a versatile and widely used programming language it’s utilised in several automation tasks.

Python scripts for automation

The word automation over is the same as the name defines it. The task eliminates the manual effort and processes automatically. The main reason developers prefer automation in Python is because it's open-source and offers built tools of libraries and different kinds of support.

So. Let's dive in depth about what kinds of tasks are done and how they can be automated.

1. Image optimizer

Beginning with images you can effortlessly enhance and manipulate your images by accessing any tools or software.


    # Image Optimising
    from PIL import Image, ImageFilter, ImageOps, ImageEnhance
    
    # Load the image
    im = Image.open("Image1.jpg")
    
    # Crop the image
    im = im.crop((34, 23, 100, 100))
    
    # Resize the image
    im = im.resize((50, 50))
    
    # Flip the image horizontally
    im = im.transpose(Image.FLIP_LEFT_RIGHT)
    
    # Rotate the image 360 degrees
    im = im.rotate(360)
    
    # Compress the image
    im.save("Image1.jpg", optimize=True, quality=90)
    
    # Apply blur effect
    im = im.filter(ImageFilter.BLUR)
    
    # Apply sharpening effect
    im = im.filter(ImageFilter.SHARPEN)
    
    # Adjust brightness
    enhancer = ImageEnhance.Brightness(im)
    im = enhancer.enhance(1.5)
    
    # Adjust contrast
    enhancer = ImageEnhance.Contrast(im)
    im = enhancer.enhance(1.5)
    
    # Add filters
    im = ImageOps.grayscale(im)
    im = ImageOps.invert(im)
    im = ImageOps.posterize(im, 4)
    
    # Save the optimised image
    im.save("Image1.jpg")
                                          

The script over here is the pillow module that uses PIL (Python Imaging Library) that allows the developers to crop, resize, flip, rotate, compress, blur, sharpen, adjust brightness, contrast, and add filters to an image.

2. Video optimizer

Python automation allows you to compress your videos for storage. Transmission or even for improvisation.


    # Video Optimizer
    import moviepy.editor as pyedit
    
    # Load the video
    video = pyedit.VideoFileClip("vid.mp4")
    
    # Trim the video
    vid1 = video.subclip(0, 10)
    vid2 = video.subclip(20, 40)
    final_vid = pyedit.concatenate_videoclips([vid1, vid2])
    
    # Speed up the video
    final_vid = final_vid.speedx(2)
    
    # Add audio to the video
    aud = pyedit.AudioFileClip("bg.mp3")
    final_vid = final_vid.set_audio(aud)
    
    # Reverse the video
    final_vid = final_vid.fx(pyedit.vfx.time_mirror)
    
    # Merge two videos
    vid1 = pyedit.VideoFileClip("vid1.mp4")
    vid2 = pyedit.VideoFileClip("vid2.mp4")
    final_vid = pyedit.concatenate_videoclips([vid1, vid2])
    
    # Add VFX to the video
    vid1 = final_vid.fx(pyedit.vfx.mirror_x)
    vid2 = final_vid.fx(pyedit.vfx.invert_colors)
    final_vid = pyedit.concatenate_videoclips([vid1, vid2])
    
    # Add images to the video
    img1 = pyedit.ImageClip("img1.jpg")
    img2 = pyedit.ImageClip("img2.jpg")
    final_vid = pyedit.concatenate_videoclips([img1, img2])
    
    # Save the final video
    final_vid.write_videofile("final.mp4")            
                                          

The script applies a moviepy module that optimises the video by trimming, changing speed, and adding audio and VFX(Visual Effects). Moreover, this library also allows you to merge, reverse and add images to it.

3. Email scheduler

This is considered one of the most powerful Python automation scripts allowing you to send emails automatically as per the schedule set. It's not just sending simple emails, but also sending greetings and reminders all this according to the schedule at a specific time.


    #Email Scheduler
    import smtplib
    import schedule
    import time
    
    def send_email():
        sender_email = "your_email@gmail.com"
        receiver_email = "recipient_email@gmail.com"
        password = "your_email_password"
    
        subject = "Automated Email"
        body = "This is an automated email sent using Python."
    
        message = f"Subject: {subject}\n\n{body}"
    
    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
            server.login(sender_email, password)
            server.sendmail(sender_email, receiver_email, message)
    
    # Schedule the email to be sent daily at 8 AM
    schedule.every().day.at("08:00").do(send_email)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
            

4. Social media auto-poster

Another powerful automation Python script over here to update your social media post and presence on multiple platforms.


    # Social Media Auto-Poster
    import tweepy
    import schedule
    import time
    
    def post_to_twitter():
        api_key = "YOUR_API_KEY"
        api_secret = "YOUR_API_SECRET"
        access_token = "YOUR_ACCESS_TOKEN"
        access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"
    
        auth = tweepy.OAuthHandler(api_key, api_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth)
    
        tweet = "This is an automated tweet using Python!"
    
        api.update_status(tweet)
    
    # Schedule the tweet to be posted every 6 hours
    schedule. every(6).hours.do(post_to_twitter)
    while True:
        schedule.run_pending()
        time.sleep(1)
            

Over here the script used is Tweety which automatically posts content on the respective social media platform mentioned at scheduled intervals.

5. PDF to image

It’s one of the common things that every organisation does frequently. So, keeping this in mind Python offers a script of pyMuPDF.


    # PDF to Images
    import fitz
    def pdf_to_images(pdf_file):
        doc = fitz.open(pdf_file)
        for page in doc:
            pix = page.get_pixmap()
            output = f"page{page.number}.png"
            pix.writePNG(output)
    pdf_to_images("test.pdf")
    It not only converts PDF to images it also allows you to extract individual pages from PDF and convert them entirely into image format.
            

Over here the script used is Tweety which automatically posts content on the respective social media platform mentioned at scheduled intervals.

6. Get API data

It’s one of the essential automation scripts while retrieving data from API. As we know, fetching data manually is quite time-consuming. Therefore python offers the script of urllib3.


    # Get API Data
    import urllib3
    
    # Fetch API data using GET request
    url = "https://api.github.com/users/psf/repos"
    http = urllib3.PoolManager()
    response = http.request('GET', url)
    print("Status Code:", response.status)
    print("Response Data:", response.data)
    
    # Post API data using POST request
    url = "https://httpbin.org/post"
    http = urllib3.PoolManager()
    response = http.request('POST', url, fields={'hello': 'world'})
    print("Status Code:", response.status)            
            

The urlib3 over here makes the HTTP request. The GET request is to fetch data and the POST request is to send data. Both requests are done on a specified URL. Whereas the status code indicates whether the request was successful or not.

7. Web scraping

Web scraping can be explained as extracting data from websites which involves automating the process of accessing web pages, extracting relevant information, and storing in a structured format.


    # Web Scraping Script
    import requests
    from bs4 import BeautifulSoup
    url = "https://example.com"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    
    # Extract specific data from the website
    data = soup.find("div", {"class": "content"})
    Python utilises the BeautifulSoup modules that extract data from websites and specific information as well.                       
            

8. Automated testing

It’s a crucial aspect of modern software development that allows developers to validate their code, detain bug issues, and reliability of the application.


    # Automated Testing with Pytest
    import pytest
    
    # Function to be tested
    def add_numbers(x, y):
        return x + y
    
    # Test cases for the function
    def test_addition():
        assert add_numbers(1, 2) == 3
        assert add_numbers(-1, 1) == 0
        assert add_numbers(0, 0) == 0
        assert add_numbers(10, 5) == 15
    if __name__ == "__main__":
        pytest.main()
            

So, over here Pytest is scripting code utilised as it’s only a testing framework for a perfect solution to test the Python code.

9. Sync and file backup

It's an automated tool designed to take the responsibility of managing your files and keeping it secure. The script Python ensures that all content is consistent between two locations by automatically backing up and syncing data between them.


    # File Backup and Sync Script
    import os
    import shutil
    
    def backup_and_sync(source_folder, backup_folder):
        for root, _, files in os.walk(source_folder):
            for file in files:
                source_path = os.path.join(root, file)
                backup_path = os.path.join(backup_folder, root.replace(source_folder, ""), file)
    
                # Create directories if they don't exist in the backup folder
                os.makedirs(os.path.dirname(backup_path), exist_ok=True)
    
                # Copy the file to the backup folder
                shutil.copy2(source_path, backup_path)
    
        # Delete files in the backup folder that are not present in the source folder
        for root, _, files in os.walk(backup_folder):
            for file in files:
                backup_path = os.path.join(root, file)
                source_path = os.path.join(source_folder, root.replace(backup_folder, ""), file)
    
                if not os.path.exists(source_path):
                    os.remove(backup_path)
    
    source_folder = "path/to/source/folder"
    backup_folder = "path/to/backup/folder"
    backup_and_sync(source_folder, backup_folder)
            

Unit test writing is made simple and intuitive with the help of the `pytest} package. Three test scenarios are defined for the `add_numbers()` function by the `test_addition()` function.

The `assert} statement verifies if the result is what was anticipated and what was produced. The test suite is executed and the results are printed by the `pytest.main()` method.

10. Download multiple images

Downloading multiple images simultaneously can be time-consuming when working manually on it. Python uses the concept of multithreading.


    from typing import List
    import uuid
    import requests
    import concurrent. Futures
    Next step is to create a list of the image sources.
    urls: List= [“/image.jpg”,
                    “/image_2.jpg”,
            ]
            

The uuid request is the built-in library that generates random image names and concurrent. futures as well library that leverages the thread pooling functionality. Using them together makes this script one of the most widely used Python automation scripts.

What lies ahead in python

If we look ahead then there is no doubt that most of the applications will be based on the Python language. From data analytics to automation are mostly Python-based.

Python has gained a strong base on Web development services making developers more dependent on Python language. Because of its dynamic universality and ability to run on almost any architecture, Python is referred to as a universal language.

Conclusion

So, the conclusion over here clearly explains that Python, that open source programming language, is the best in automation that is taking over tech services.

So, now if you are willing to Hire a Python developer then Techvoot solutions is the word where experts await to create the best app on Python just the way you and your organisation wanted and expected for it.

FAQ

Yes, python is known for its readability and ease of learning. You can start with beginner-friendly and then gradually use these scripts.

Yes, Python is a cross-platform, where these scripts can be used on Windows, macOS and Linux.

Some familiarity with programming helps you out in working on these scripts making it more accessible to non-programmers as well.

Yes, python is known for its flexibility where you can customise them before meeting your unique requirements.

Dhaval Baldha
Dhaval Baldha

Co-Founder at Techvoot solutions

Dhaval Baldha is Co-Founder of Techvoot Solutions. Delivering innovative and successful technology solutions using his expertise in software development, system architecture, and project management.

Linkedin
Hire Skilled Developer

*Please fill all the required fields

Get our Newsletter

Customized solutions for your projects

*Please fill all the required fields