10 Killer Python Automation Scripts!

In the fast-paced modern life, repetitive tasks act like invisible “time thieves,” quietly consuming our work efficiency and creative enthusiasm. When faced with mechanical operations such as data organization and file archiving, manual processing not only easily leads to burnout but may also result in inefficiency due to negligence. Fortunately, Python, with its rich standard libraries and third-party packages, provides an elegant solution for automating processes.

This article will select 10 typical life scenarios and guide you through building automated workflows using a three-dimensional interpretation model of “problem scenario + code example + effect demonstration.” From intelligently organizing messy work documents to automatically scraping web information; from sending reminder emails on a schedule to batch processing images and videos, each case is carefully designed: it includes core skills such as using openpyxl for spreadsheet processing and requests for fetching web resources, while strictly adhering to the minimalist philosophy of “three lines of code to solve a problem.” Whether you are a newcomer in the workplace needing to free yourself from basic tasks or an efficiency enthusiast pursuing workflow optimization, these practical cases will help you unlock a “one-click” operation experience, truly allowing machines to handle repetitive labor and letting humans focus on value creation.

1. Image Optimizer

# Image Optimizer
# First install the Pillow library
# pip install Pillow
from PIL import Image, ImageEnhance, ImageFilter, ImageOps
# Open an image
im = Image.open("Image1.jpg")
# Crop
im_cropped = im.crop((34, 23, 100, 100))
# Resize
im_resized = im.resize((50, 50))
# Flip
im_flipped = im.transpose(Image.FLIP_LEFT_RIGHT)
# Blur
im_blurred = im.filter(ImageFilter.BLUR)
# Sharpen
im_sharpened = im.filter(ImageFilter.SHARPEN)
# Set brightness
enhancer = ImageEnhance.Brightness(im)
im_brightened = enhancer.enhance(1.5)  # Increase brightness by 50%
# Save processed images
im_cropped.save("image_cropped.jpg")
im_resized.save("image_resized.jpg")

This image batch processing tool developed based on the Python Pillow library provides basic image processing functions such as cropping, resizing, flipping, and brightness adjustment. By combining command line parameters, it can quickly complete batch editing of photos without relying on professional image software.

Suppose you just returned from a trip with many photos to organize. You want to crop some photos to the right size and enhance their brightness to share with friends. This script can help you quickly accomplish these tasks, making your photos look more professional.

2. Video Optimizer

# Video Optimizer
# First install the MoviePy library
# pip install moviepy
import moviepy.editor as pyedit
# Load video
video = pyedit.VideoFileClip("vid.mp4")
# Trim video
vid1 = video.subclip(0, 10)
vid2 = video.subclip(20, 40)
final_vid = pyedit.concatenate_videoclips([vid1, vid2])
# Speed up video
final_vid = final_vid.speedx(2)
# Add audio to video
aud = pyedit.AudioFileClip("bg.mp3")
final_vid = final_vid.set_audio(aud)
# Save video
final_vid.write_videofile("final_video.mp4")

This script builds a lightweight video editing toolchain based on the MoviePy video processing library, achieving professional-level video processing functions through Python code, including precise timeline editing, multi-track audio synthesis, and speed effect applications. Its modular design allows for flexible combinations of processing steps, forming a complete workflow from material selection to final output, completely freeing users from the interface dependency and learning costs of traditional video editing software.

In the context of creating travel vlogs, this script demonstrates significant creative advantages: when faced with hours of raw footage, simply defining a list of timestamps can quickly extract highlight segments; through the audio track overlay function, on-site sound effects can be seamlessly blended with selected background music; combined with speed adjustment features, lengthy transition shots can be compressed to highlight exciting moments. For example, it can condense 30 minutes of raw footage into a 3-minute highlight version while adding dynamic music and transition effects, ultimately generating a high-quality short video suitable for social media dissemination. Its output format supports flexible adjustments, allowing direct export to optimized versions suitable for platforms like WeChat and Douyin, enabling ordinary users to achieve professional-level video creation through code, bringing more creative possibilities to content sharing.

3. PDF to Image

# PDF to Image
# First install the PyMuPDF library
# pip install PyMuPDF
import fitz
def pdf_to_images(pdf_file):
    doc = fitz.open(pdf_file)
    for p in doc:
        pix = p.get_pixmap()
        output = f"page{p.number}.png"
        pix.writePNG(output)
# Convert PDF file
pdf_to_images("test.pdf")

This script, based on the efficient document processing library PyMuPDF (fitz), implements the automation of converting PDF files to PNG images page by page. Its core logic supports custom resolution, color mode, and other parameter configurations, accurately preserving the layout and visual details of the original PDF, especially suitable for scenarios requiring high-quality image, chart, or layout extraction from documents.

When faced with complex PDF documents containing mixed text and images (such as academic papers, e-books, design drafts, etc.), this script can replace the tedious process of manually taking screenshots page by page — simply specify the target file path, and it can generate high-definition PNG images corresponding to the PDF page numbers with one click, each image fully retaining the original page’s fonts, images, tables, and other elements. Its batch processing capability significantly enhances content extraction efficiency, whether for archiving charts in academic materials, previewing design drafts, or cross-platform display of electronic documents, it can automate the conversion to avoid repetitive labor, ensuring the standardization and usability of output resources. The script’s lightweight design supports processing large PDF files, combined with PyMuPDF’s high-performance rendering engine, achieving high-quality image output while keeping file sizes manageable, making it a practical tool prototype for document digitization.

4. Fetch API Data

# Fetch API Data
# First install the requests library
# pip install requests
import requests
# Set API URL
url = "https://api.github.com/users/psf/repos"
# Send GET request
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
    repos = response.json()  # Parse the returned JSON data into a Python object
    for repo in repos:
        print(f"Repository Name: {repo['name']}, Stars: {repo['stargazers_count']}")
else:
    print(f"Request failed, status code: {response.status_code}")

This script implements efficient interaction with the GitHub API based on the <span>requests</span> library, encapsulating core logic such as API authentication, request sending, status code verification, and data parsing to accurately retrieve details of a specified user’s repositories. Its design includes a pagination handling mechanism to cope with large-scale data returns, while integrating exception handling features to ensure the stability of API calls, fully demonstrating the API-driven data retrieval process in modern web development.

In the context of evaluating open-source projects, this script provides a practical tool for quantitative analysis: simply input the target user or organization name to batch extract key metrics such as repository names, star counts, fork counts, and last update times, intuitively reflecting the project’s community activity, technical influence, and maintenance status. For example, by filtering the top 10 repositories by star count, one can quickly locate high-attention projects; comparing the update frequency of different repositories can assist in judging the project’s ongoing maintenance capability. The structured data output (such as JSON format) supports direct integration with data analysis tools or visualization platforms, providing data support for technical selection, competitive research, or community operations, significantly enhancing the efficiency and scientific nature of open-source project evaluations.

5. Battery Indicator

# Battery Indicator
# First install the plyer and psutil libraries
# pip install plyer psutil
from plyer import notification
import psutil
from time import sleep
while True:
    battery = psutil.sensors_battery()
    life = battery.percent
    if life < 20:
        notification.notify(
            title="Low Battery",
            message="Please connect to power!",
            timeout=10
        )
    sleep(60)  # Check every 60 seconds

This script implements real-time tracking of device battery status through the <span>psutil</span> system monitoring library and uses the <span>plyer</span> cross-platform tool to implement intelligent notification functionality, building a lightweight low battery warning system. Its core logic can accurately obtain key information such as remaining battery power, charging status, and runtime, automatically triggering desktop notifications to remind users to charge when the battery level falls below a preset threshold (e.g., 20%), effectively avoiding sudden power outages due to depleted battery.

In remote work, online meetings, or mobile office scenarios, this script demonstrates significant practical value: by continuously monitoring battery status and providing instant warnings, it ensures that users do not interrupt their work due to low battery when handling important tasks — whether it is a sudden disconnection during a video conference or loss of unsaved data while editing documents, this automated reminder mechanism can help avoid such issues in advance. Its modular design allows for flexible adjustment of warning thresholds and notification content, adapting to various devices such as laptops and tablets, becoming a thoughtful tool to enhance the stability of mobile office, allowing users to focus on tasks without frequently checking battery status.

6. Grammar Fixer

# Grammar Fixer
# First install the happytransformer library
# pip install happytransformer
from happytransformer import HappyTextToText as HappyTTT
from happytransformer import TTSettings
def grammar_fixer(text):
    grammar_model = HappyTTT("T5", "prithivida/grammar_error_correcter_v1")
    config = TTSettings(do_sample=True, top_k=10, max_length=100)
    corrected = grammar_model.generate_text(text, args=config)
    print("Corrected Text:", corrected.text)
text_to_fix = "This is smple tet we how know this"
grammar_fixer(text_to_fix)

This script is built on the natural language processing library HappyTransformer, implementing intelligent grammar correction functionality based on deep learning models — it can automatically detect and correct grammar errors, punctuation misuse, and inappropriate word choices in the text, providing precise correction suggestions through contextual semantic analysis, effectively improving the grammatical correctness, fluency, and professionalism of the text.

In scenarios such as writing academic papers, business documents, or study abroad application materials where grammatical standards are high, this script becomes a reliable auxiliary tool: without manually checking sentence by sentence, simply inputting the text can trigger a multi-dimensional grammar detection process, accurately locating common issues such as subject-verb disagreement, tense errors, and improper preposition collocations, and generating optimization plans based on the rich corpus trained by the model. Its core advantage lies in supporting long text paragraph processing, combined with HappyTransformer’s contextual awareness capabilities, ensuring that correction results align with semantic logic, avoiding semantic deviations caused by mechanical corrections. Whether for students to enhance the normative quality of academic writing or for professionals to optimize business communication materials, this script can significantly reduce manual verification costs through automated grammar proofreading technology, making written expression more rigorous and professional.

7. Spelling Correction

# Spelling Correction
# First install the textblob library
# pip install textblob
from textblob import TextBlob
# Correct paragraph spelling
def fix_paragraph(paragraph):
    sentence = TextBlob(paragraph)
    correction = sentence.correct()
    print(correction)
# Correct word spelling
def fix_word(word):
    from textblob import Word
    corrected_word = Word(word).correct()
    print(corrected_word)
fix_paragraph("This is sammple tet!!")
fix_word("maangoo")

This script is built on the natural language processing library TextBlob, implementing intelligent spelling correction functionality — it supports batch detection and correction of paragraph-level text as well as precise proofreading of individual words, providing contextually relevant correction suggestions through semantic analysis, effectively improving the accuracy and professionalism of written text.

In writing social media copy, email content, or document materials, this script can serve as an efficient auxiliary tool: without manually checking word by word, simply inputting the text can trigger an automated spelling check process, quickly locating and correcting common spelling errors, grammatical flaws, or typing mistakes. Its lightweight design supports real-time response, and combined with TextBlob’s multilingual processing capabilities, it can also address spelling correction needs in mainstream languages like English. Whether for content creators to optimize output quality or for ordinary users to avoid expression issues due to spelling problems, this script can simplify the proofreading process through automation, making written communication more standardized and fluent.

8. Internet Downloader

# Internet Downloader
# First install the internetdownloadmanager library
# pip install internetdownloadmanager
import internetdownloadmanager as idm
def downloader(url, output):
    pydownloader = idm.Downloader(worker=20,
                                   part_size=1024*1024*10,
                                   resumable=True,)
    pydownloader.download(url, output)
downloader("http://example.com/image.jpg", "image.jpg")
downloader("http://example.com/video.mp4", "video.mp4")

This script builds a lightweight download management tool based on the <span>internetdownloadmanager</span> library, significantly improving the efficiency of large file transfers through multi-threaded concurrent download technology, while integrating a resume mechanism to ensure the stability and completeness of download tasks. Its core logic encapsulates task queue management, progress monitoring, and exception handling functions, supporting custom file save paths, concurrent thread counts, and other parameter configurations, providing flexible solutions for batch file downloads.

When handling GB-level large files or batch resource downloads, this script demonstrates significant advantages: by breaking through the single-thread rate bottleneck through multi-threaded segmented transmission technology, combined with intelligent retry strategies to automatically cope with network fluctuations, it ensures complete file downloads without manual monitoring. Its modular design allows developers to easily extend functionality, such as adding download progress visualization interfaces, task priority management, or download completion notifications. Whether for daily resource acquisition or batch synchronization of files in projects, this script can effectively simplify operational processes and enhance data transfer efficiency, becoming a reliable automated download tool prototype.

9. Fetch World News

# Fetch World News
# First install the requests library
# pip install requests
import requests
ApiKey = "YOUR_API_KEY"
url = f"https://api.worldnewsapi.com/search-news?text=hurricane&amp;api-key={ApiKey}"
headers = {
    'Accept': 'application/json'}
response = requests.get(url, headers=headers)
print("News:", response.json())

This script leverages the <span>requests</span> library to efficiently interact with news APIs, supporting flexible filtering of target news data by theme, keyword, time range, and other conditions through simple parameter configurations. Its core logic encapsulates the processes of sending HTTP requests, parsing responses, and formatting data, ensuring that developers can quickly obtain structured real-time news information.

For users or projects concerned with current events, this script provides an automated news retrieval solution — without visiting news websites one by one, it can aggregate real-time information from multiple sources, covering diverse fields such as technology, finance, and entertainment. By modifying request parameters, it can accurately pinpoint hot events on specific themes or regions, achieving targeted news content scraping and real-time updates, effectively enhancing information retrieval efficiency and providing underlying data support for public opinion analysis, content creation, or personalized news tool development.

10. PySide2 GUI

# PySide2 GUI
# First install the PySide2 library
# pip install PySide2
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QLineEdit, QRadioButton, QCheckBox, QSlider, QProgressBar
import sys
app = QApplication(sys.argv)
window = QWidget()
# Adjust window size
window.resize(500, 500)
# Set window title
window.setWindowTitle("PySide2 Window")
# Add button
button = QPushButton("Click Me", window)
button.move(200, 200)
# Add label
label = QLabel("Hello Medium", window)
label.move(200, 150)
# Add input box
input_box = QLineEdit(window)
input_box.move(200, 250)
# Add radio button
radio_button = QRadioButton("Radio Button", window)
radio_button.move(200, 300)
# Add checkbox
checkbox = QCheckBox("Checkbox", window)
checkbox.move(200, 350)
# Add slider
slider = QSlider(window)
slider.move(200, 400)
# Add progress bar
progress_bar = QProgressBar(window)
progress_bar.move(200, 450)
# Show window
window.show()
sys.exit(app.exec())

This script, based on the PySide2 cross-platform GUI toolkit, implements a basic graphical user interface application framework, fully demonstrating the integration methods of core interactive components such as buttons, labels, and input boxes. Through clear code structure and comments, it intuitively presents the implementation logic of UI layout design, signal-slot mechanism, and event response, providing developers with a reusable GUI building template.

For scenarios requiring user-friendly interfaces for projects or tools, this script can serve as a starting point for rapid prototype development — with simple modifications to component properties and business logic, it can build interactive interfaces with data input, operation triggers, and status feedback functionalities. Its modular design lowers the barrier to GUI development, making it suitable for beginners to learn the basics of desktop application development, while also helping experienced developers efficiently complete the interface layer construction, significantly enhancing the usability and professionalism of tools.

Conclusion

The above ten Python automation scripts cover diverse fields such as image processing, video editing, API interaction, system monitoring, natural language processing, download management, news scraping, and graphical user interface development. These scripts are suitable for programming novices as practical cases for entry-level learning, and can also serve as practical tools to enhance efficiency in daily work — from basic file processing to complex data interactions, each script contains clear comments and modular designs, making it easy to understand core logic and functionality implementation.

I hope these examples inspire you to explore Python automation further, transforming more repetitive tasks into efficient code implementations! I encourage you to modify script parameters, expand functional modules, and personally experience the creative joy that programming brings — you might discover unexpected new insights! Whether optimizing existing features or developing custom tools based on actual needs, the flexible combination of code can always bring surprises. Maintain an exploratory spirit and let Python be a powerful assistant in liberating productivity!

Leave a Comment