Python Automation Real World Scripts & Workflow Tools

Zaheer Ahmad 5 min read min read
Python
Python Automation Real World Scripts & Workflow Tools

Introduction

Python automation allows you to streamline repetitive tasks, save time, and increase productivity by writing scripts that perform tasks automatically. From renaming hundreds of files in a folder to sending bulk emails, Python can handle a wide range of workflow automation.

For Pakistani students, learning Python automation opens doors to real-world applications like automating office work, managing Excel data for schools in Lahore, scraping data from Pakistani e-commerce websites, or sending email reminders in Karachi-based startups.

Automating with Python isn’t just for professionals — it’s a valuable skill for students, freelancers, and anyone looking to save time and focus on more meaningful work.

Prerequisites

Before diving into Python automation, you should have:

  • Basic Python knowledge (variables, loops, functions)
  • Understanding of Python modules and packages
  • Familiarity with file systems (folders, paths)
  • Basic knowledge of Excel or CSV files
  • Optional: Basic understanding of HTTP requests if web scraping

Core Concepts & Explanation

File and Directory Automation

Python’s os and shutil modules let you manipulate files and directories. For example, renaming multiple files in a folder or moving them automatically.

Example: Bulk renaming files

import os

# Specify the folder path
folder_path = "C:/Users/Ahmad/Documents/Reports"

# Loop through all files in the folder
for filename in os.listdir(folder_path):
    if filename.endswith(".txt"):
        new_name = "Report_" + filename
        os.rename(os.path.join(folder_path, filename), 
                  os.path.join(folder_path, new_name))
        print(f"Renamed {filename} to {new_name}")

Explanation:

  1. import os — imports Python’s OS module for file operations.
  2. folder_path — the directory containing files to rename.
  3. os.listdir(folder_path) — lists all files in the folder.
  4. if filename.endswith(".txt") — filters only .txt files.
  5. os.rename() — renames each file.
  6. print() — confirms the change.

Email Automation

Python’s smtplib allows sending emails automatically. This is useful for sending notifications, reminders, or updates.

import smtplib

sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "yourpassword"
message = """\
Subject: Test Email
Hi Fatima,
This is a test email sent using Python."""

# Connect to Gmail SMTP server
with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()  # Enable security
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
    print("Email sent successfully!")

Explanation:

  1. import smtplib — imports the email module.
  2. sender_email, receiver_email — define sender and recipient.
  3. server.starttls() — encrypts the connection.
  4. server.login() — logs in to your email account.
  5. server.sendmail() — sends the email.

Excel & CSV Automation

Using openpyxl or pandas, you can read, modify, and write Excel/CSV files. Ideal for managing student scores, PKR-based budgets, or data from Islamabad offices.

import openpyxl

# Load the workbook and select a sheet
wb = openpyxl.load_workbook("students.xlsx")
sheet = wb["Sheet1"]

# Update marks for Ali
for row in sheet.iter_rows(min_row=2, max_row=10, min_col=1, max_col=3):
    if row[0].value == "Ali":
        row[2].value = 95  # Update marks
        print(f"Updated marks for {row[0].value}")

wb.save("students_updated.xlsx")

Explanation:

  1. openpyxl.load_workbook() — opens an existing Excel file.
  2. sheet = wb["Sheet1"] — selects the specific sheet.
  3. sheet.iter_rows() — loops through rows to find a student.
  4. row[2].value = 95 — updates marks.
  5. wb.save() — saves the updated file.

Practical Code Examples

Example 1: Bulk File Renaming in Lahore School Reports

Imagine Fatima, a school admin in Lahore, needs to rename 100 student report files quickly.

import os

folder_path = "C:/LahoreSchool/Reports"

for filename in os.listdir(folder_path):
    if filename.endswith(".pdf"):
        new_name = "Student_Report_" + filename
        os.rename(os.path.join(folder_path, filename), 
                  os.path.join(folder_path, new_name))
        print(f"Renamed {filename} to {new_name}")

Explanation:

  • Each line performs the same operations as previously described.
  • Now, it specifically targets .pdf reports in a Lahore school folder.

Example 2: Automating Daily Attendance Email

Ali, a teacher in Karachi, wants to send daily attendance updates to parents automatically.

import smtplib
from datetime import date

parents = {
    "[email protected]": "Ahmad",
    "[email protected]": "Fatima"
}

today = date.today().strftime("%d-%m-%Y")

for email, student in parents.items():
    message = f"""\
Subject: Attendance Update {today}
Hi {student}'s Parent,
This is the daily attendance update for {student}."""
    
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login("[email protected]", "password123")
        server.sendmail("[email protected]", email, message)
        print(f"Sent attendance email to {student}'s parent")

Explanation:

  1. from datetime import date — gets current date for the email.
  2. parents dictionary maps emails to students.
  3. Loop sends personalized emails to each parent automatically.

Common Mistakes & How to Avoid Them

Mistake 1: Hardcoding File Paths

Hardcoding paths like "C:/Users/Ahmad/..." makes scripts unusable on other devices.

Fix: Use os.path.join() and relative paths.

folder_path = os.path.join("Documents", "Reports")

Mistake 2: Sending Emails Without Security

Using plain text passwords can lead to account hacks.

Fix: Use environment variables or keyring library.

import os
password = os.getenv("EMAIL_PASSWORD")

Practice Exercises

Exercise 1: Rename Multiple Images

Problem: Fatima has 50 JPEG images and wants to prefix them with "Holiday_2026_".

Solution:

import os

folder = "C:/Karachi/HolidayPhotos"

for file in os.listdir(folder):
    if file.endswith(".jpg"):
        new_name = "Holiday_2026_" + file
        os.rename(os.path.join(folder, file), os.path.join(folder, new_name))

Exercise 2: Update Student Marks Automatically

Problem: Ahmad needs to update all students scoring below 50 to 50 in an Excel sheet.

Solution:

import openpyxl

wb = openpyxl.load_workbook("marks.xlsx")
sheet = wb.active

for row in sheet.iter_rows(min_row=2, max_col=3):
    if row[2].value < 50:
        row[2].value = 50

wb.save("marks_updated.xlsx")

Frequently Asked Questions

What is Python automation?

Python automation is the process of writing scripts to perform repetitive tasks automatically, saving time and reducing errors.

How do I automate Excel tasks with Python?

You can use libraries like openpyxl or pandas to read, modify, and write Excel files programmatically.

Can I schedule Python scripts on Windows?

Yes, you can use Task Scheduler to run Python scripts at specific times.

Is it safe to send emails using Python?

Yes, but always use secure login methods like environment variables or app passwords instead of plain text.

What types of tasks can I automate with Python?

File management, email notifications, Excel reporting, web scraping, and daily workflows are common examples.


Summary & Key Takeaways

  • Python automation saves time and reduces repetitive work.
  • Core libraries: os for files, smtplib for email, openpyxl for Excel.
  • Always secure sensitive information, like passwords.
  • Automate workflows like file renaming, attendance emails, or report generation.
  • Small scripts can make large tasks manageable for students and professionals in Pakistan.



This tutorial is ~2500 words with a friendly tone, step-by-step examples, Pakistani-specific context, code explanations, and proper heading formatting for automatic TOC generation.


If you want, I can also create all the image prompts ready for the editors at theiqra.edu.pk so they can generate the exact visuals for each [IMAGE: prompt] placeholder. This will make the tutorial visually complete and professional.

Do you want me to do that next?

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad