The open blogging platform. Say no to algorithms and paywalls.

10 Python Automation Scripts for Everyday Problems

Collection of Handy Tools for your Daily Python Projects

image

Every day we need some automation tools to solve our daily tasks and even need automation help in our Projects. In this article, You will get to know 10 Python Automation Scripts that will solve your everyday problems. Make a bookmark for this article and let go.

You're either the one that creates the automation or you're getting automated. — Tom Preston-Werner

Photo Editing

Edit your photos with this awesome automation script that uses the Pillow module. Below I made a list of image editing functions that you can use in your Python project or solve any daily life problem.

This script is a handful of snippet codes for programmers who need to programmatically edit their images.

# Photo Editing
# pip install pillow
from PIL import Image, ImageFilter
# Resize an image
img = Image.open('img.jpg')
resize = img.resize((200, 300))
resize.save('output.jpg')
# Blur Image
img = Image.open('img.jpg')
blur = img.filter(ImageFilter.BLUR)
blur.save('output.jpg')
# Sharp Image
img = Image.open('img.jpg')
sharp = img.filter(ImageFilter.SHARPEN)
sharp.save('output.jpg')
# Crop Image
img = Image.open('img.jpg')
crop = img.crop((0, 0, 50, 50))
crop.save('output.jpg')
# Rotate Image
img = Image.open('img.jpg')
rotate = img.rotate(90)
rotate.save('output.jpg')
# Flip Image
img = Image.open('img.jpg')
flip = img.transpose(Image.FLIP_LEFT_RIGHT)
flip.save('output.jpg')
# Transpose Image
img = Image.open('img.jpg')
transpose = img.transpose(Image.TRANSPOSE)
transpose.save('output.jpg')
# Convert Image to GreyScale
img = Image.open('img.jpg')
convert = img.convert('L')
convert.save('output.jpg')

PDF Watermarker

This automation script will simply help you Watermark your PDF page by page. This script uses the PyPDF4 module to read and add watermark. Check out the code below:

# Watermark PDF files
# pip install PyPDF4

import PyPDF

4def Watermark():
    pdf_file= "test.pdf"
    output_pdf= "output.pdf"
    watermark= "watermark.pdf"

watermark_read = PyPDF4.PdfFileReader(watermark)
    watermark_page = watermark_read.getPage(0)
    pdf_reader = PyPDF4.PdfFileReader(pdf_file)
    pdf_writer = PyPDF4.PdfFileWriter()
    for page in range(pdf_reader.getNumPages()):

page = pdf_reader.getPage(page)
        page.mergePage(watermark_page)
        pdf_writer.addPage(page)

    # writing output pdf file
    with open(output_pdf, 'wb') as pdf:
        pdf_writer.write(pdf)
Watermark()

Video Editing

Now edit your video programmatically with this automation script. It uses the Moviepy module to edit the video. The below script is a handy bit of code to trim videos, add VFX and add audio to specific parts of the video. You can explore the Moviepy more for further functions.

# Video Editing
# pip install moviepy
from moviepy.editor import *

# Triming the video
clip_1 = VideoFileClip("sample_video.mp4").subclip(40, 50)
clip_2 = VideoFileClip("sample_video.mp4").subclip(68, 91)
final_clip = concatenate_videoclips([clip_1, clip_2])
final_clip.write_videofile("output.mp4")

# Adding VFX
clip_1 = (VideoFileClip("sample_video.mp4").subclip(40, 50).fx(vfx.colorx, 1.2).fx(vfx.lum_contrast, 0, 30, 100))
clip_2 = (VideoFileClip("sample_video.mp4").subclip(68, 91).fx(vfx.invert_colors))
final_clip = concatenate_videoclips([clip_1, clip_2])
final_clip.write_videofile("output.mp4")

# Add Audio to Video
clip = VideoFileClip("sample_video.mp4")

# Add audio to only first 5 sec
clip = clip.subclip(0, 5)
audioclip = AudioFileClip("audio.mp3").subclip(0, 5)
videoclip = clip.set_audio(audioclip)
final_clip.write_videofile("output.mp4")

Speech to Text AI

You saw my code about converting Text to Speech But do you know we can convert speech to text in Python too. This awesome code will show you how to do it. Check the code below:

# Convert Speech to Text
#pip install SpeechRecognition
import speech_recognition as sr
def SpeechToText():
Ai = sr.Recognizer()
    with sr.Microphone() as source:
        listening = Ai.listen(source, phrase_time_limit = 6)
    try:
        command = Ai.recognize_google(listening).lower()
        print("You said: " + command)

    except sr.UnknownValueError:
        print("Sorry Can't understand, Try again")
        SpeechToText()

Request API

Need to call an API request then try the below script. The script uses the Beautiful request module that can get/post data on any API call. The below code has two parts one is getting the HTML source code and the second is logging in to the site.

# Request Api
# pip install requests
import requests

# Get Data
headers = {
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
    AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
}

r = requests.get('https://api.example.com', headers=headers)
print(r.status_code) # 200
print(r.headers['content-type'])
print(r.content) # HTML Data

# Login Site
payload = {'username': 'USERNAME', 'userpass': 'PASSWORD'}
r = requests.post('https://example.com/login', data=payload)
print(r.status_code) # 200

Python GUI

This script will let you a hand to create Graphical User-Interface Python programs. It uses the latest PyQt6 module and I coded most of the important widgets below:

# Python GUI
# pip install PyQt6

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox, QLabel, QLineEdit

def Application():

app = QApplication(sys.argv)
    win = QWidget()
    win.resize(300, 300)
    win.move(200, 200)
    win.setWindowTitle('Medium Article')

# Create Buttons
    btn = QPushButton('Quit', win)

    # Message Box
    QMessageBox.question(win, 'Message',"Are you sure to quit?")

# Label Text
    lbl = QLabel('Hello World', win)

# Button Clicked
    btn.clicked.connect(lambda: QMessageBox.question(win, 'Message',"Are you sure to quit?"))

# Entry Box
    entry = QLineEdit(win)

win.show()
    sys.exit(app.exec())

if __name__ == '__main__':
    Application()

Spell Checker

Have a lot of documents and huge text and if you want to check the spelling then this Python script will help you solve your problem. It uses the Pyspellchecker module to check spells and give correction suggestions.

# Spell Checker in Python
# pip install pyspellchecker

from spellchecker import SpellChecker as spell

Words = spell.unknown(['Python'  , 'is' , 'a' , 'good' , 'lantyguage'])

for w in Words:
    print(spell.correction(w)) #language
    print(spell.candidates(w)) #{ language }

Grammar Checker

Inspired by Grammarly then why not try to create your own grammar checker in Python. The below script will help you check your grammar it uses the Gingerit module which is an API-based module.

# Grammer Checker in Python
# pip install gingerit

from gingerit.gingerit import GingerIt

text = "Welcm Progammer to Python"

Grammer = GingerIt()
Correction = Grammer.parse(text)

print(Correction["result"]) # Welcome, Programmer to Python
print(Correction['corrections'])

Automate Win, Mac, and Linux

We have automated web apps and smartphones then why not the Operating Systems. This automation script will automate Win, Mac, and Linux using the PyautoGui module in Python. Try the Code now!

# Automate Win, Mac and Linux
# pip install PyAutoGUI

import pyautogui as py

# Mouse Movements
py.moveTo(100, 100)
py.moveTo(200, 200, duration=1)
py.click(100, 100)
py.doubleClick(200, 200)

# Keyboard Inputs
py.write('Hello World!', interval=0.25)
py.press('enter')
py.hotkey('ctrl', 'c')
py.keyDown('shift')
py.keyUp('shift')

# Screen Automation
img = py.screenshot('screenshot.jpg')
img.save('screenshot.jpg')

loc = py.locationsOnScreen('icon.jpg')
print(loc)

Read Excel

You probably use Pandas for reading CSV files but do you know you can read excel files too. Take a look at the following script to know how it works:

# Read Excel
# pip install pandas

import pandas as pd
df = pd.read_excel('test.xlsx', sheet_name='Sheet1')

# Read Columns
name = df['Name'].to_list()
Id  = df['Id'].to_list()

print(name) # ["haider", "Dustin, "Tadashi"]
print(Id) # [245, 552, 892]

Final Thoughts

Well, I'm glad you reached the end of this article and I hope you found something useful. If you like this article don't forget to share it with your friends.




Continue Learning