Sunday, 1 March 2026

Automation made Easy!🚶‍➡️

Python Automation Handson

Python Automation Handson #1

Hour 1: Renaming all files in a directory


import os

folder = "F:\\2026\\python-automation\\ex1-rename"  ## change Your right folder name here 

for file in os.listdir(folder):
    if file.endswith(".txt"):
        new_name = "new_" + file
        os.rename(os.path.join(folder, file),
                  os.path.join(folder, new_name))
print("Done!!!")

Quiz: Which module is used for file handling?

os
pandas
sqlite

Hour 2: Marks Analyzer (Excel - XLSX)


#pip install pandas openpyxl
# xlsx file with two columns with headings Name, Marks
import pandas as pd
df = pd.read_excel("F:\\2026\\python-automation\\ex2\\students.xlsx")
print(df.head())
# Calculate average
avg = df["Marks"].mean()
print("Average Marks:", avg)
print("First mark: ", df["Marks"].max())
print("Last mark: ", df["Marks"].min())

Quiz: Which library is used to work with Excel (.xlsx) files in this program?

openpyxl
os
csv

Hour 3: Email Automation (Gmail SMTP)


import smtplib
import getpass

# Take input at runtime
sender_email = input("Enter your Gmail address: ")
password = getpass.getpass("Enter your App Password: ")
receiver_email = input("Enter receiver email: ")

# Create SMTP connection
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()

# Login
server.login(sender_email, password)

# Email content
subject = "Test"
body = "This is automated mail."
message = f"Subject: {subject}\n\n{body}"

# Send email
server.sendmail(sender_email, receiver_email, message)

# Close server
server.quit()

print("Email sent successfully!")

Quiz: Which module is used to send emails in Python?

smtplib
os
openpyxl

Hour 4: Web Automation (Selenium)


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

# Create browser instance (Make sure ChromeDriver is installed)
driver = webdriver.Chrome()

# Open website
driver.get("https://www.google.com")

time.sleep(2)

# Find search box and enter text

search_box = driver.find_element(By.NAME, "q")

search_box.send_keys("Python Automation")

search_box.send_keys(Keys.RETURN)

time.sleep(5)

# Close browser
driver.quit()

print("Web Automation Completed!!!")

Quiz: Which library is used for web automation in this program?

selenium
requests
os

Hour 5: Automatic Excel Updation (Marks → Words)


from openpyxl import load_workbook
from num2words import num2words

file_path = "F:\\2026\\python-automation\\ex2\\students.xlsx"  # Change path if needed

# Load workbook
wb = load_workbook(file_path)
sheet = wb.active

# Add new column header
sheet["C1"] = "Marks in Words"

# Read marks and convert to words
for row in sheet.iter_rows(min_row=2):
    marks_cell = row[1]   # Assuming Marks are in column B
    marks = marks_cell.value
    if marks is not None:
        words = num2words(marks)
        sheet.cell(row=marks_cell.row, column=3).value = words

# Save file
wb.save(file_path)

print("Excel Updated Successfully!!!")

Quiz: Which library is used to convert numbers into words?

num2words
openpyxl
smtplib

Week 6: Bulk Email Sender from Excel - announcements.


import smtplib
import getpass
from openpyxl import load_workbook
file_path = "F:\\2026\\python-automation\\emails.xlsx"
# Load Excel file
wb = load_workbook(file_path)
sheet = wb.active
sender_email = input("Enter your Gmail: ")
password = getpass.getpass("Enter App Password: ")
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(sender_email, password)
# Loop through Excel rows
for row in sheet.iter_rows(min_row=2, values_only=True):
    name, receiver_email = row
    subject = "Welcome"
    body = f"Hello {name},\nThis is an automated email."
    message = f"Subject: {subject}\n\n{body}"

    server.sendmail(sender_email, receiver_email, message)

server.quit()

print("Bulk Emails Sent Successfully!!!")

Quiz: Which function is used to send email?

sendmail
rename
quit

Hour 7: Automatic PDF Report Generator


from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.platypus import Table
file_path = "F:\\2026\\python-automation\\report.pdf"
doc = SimpleDocTemplate(file_path)
elements = []
styles = getSampleStyleSheet()
elements.append(Paragraph("Student Report", styles["Title"]))
elements.append(Spacer(1, 20))
data = [
    ["Name", "Marks"],
    ["Arun", "85"],
    ["Priya", "92"],
    ["Kumar", "74"]
]
table = Table(data)
elements.append(table)
doc.build(elements)
print("PDF Generated Successfully!!!")

Quiz: Which library is used to create PDF files?

reportlab
openpyxl
selenium

Hour 8: Automatic File Organizer


#pip install pip install reportlab
import os
import shutil

folder = "F:\\Downloads"

for file in os.listdir(folder):
    file_path = os.path.join(folder, file)

    if file.endswith(".pdf"):
        dest = os.path.join(folder, "PDFs")
        os.makedirs(dest, exist_ok=True)
        shutil.move(file_path, dest)

    elif file.endswith(".jpg") or file.endswith(".png"):
        dest = os.path.join(folder, "Images")
        os.makedirs(dest, exist_ok=True)
        shutil.move(file_path, dest)

print("Files Organized Successfully!!!")

Quiz: Which module is used to move files?

shutil
smtplib
getpass

Hour 9: Automatic Folder Backup & ZIP Creator


#pip install shutil

import os

import shutil

from datetime import datetime

# Folder to backup

source_folder = "F:\\2026\\python-automation\\project"

# Backup destination folder

backup_root = "F:\\2026\\python-automation\\backups"

# Create date-based folder name

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

backup_folder = os.path.join(backup_root, "backup_" + today)

# Create backup folder

shutil.copytree(source_folder, backup_folder)

# Create ZIP file

zip_path = backup_folder + ".zip"

shutil.make_archive(backup_folder, 'zip', backup_folder)

print("Backup and ZIP Created Successfully!!!")

Quiz: Which function is used to create a ZIP archive?

make_archive
copytree
rename

Hour 10: Website Data Scraper (Save to Excel)


# pip install requests beautifulsoup4 pandas openpyxl lxml
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = "https://www.annamalaiuniversity.ac.in/E02_factmem.php?dc=E02"
print("Downloading Staff List...")
# Add browser header (important)
headers = {
    "User-Agent": "Mozilla/5.0"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")
data = []
# Find table
table = soup.find("table")
if table:
    rows = table.find_all("tr")
    for row in rows:
        cols = row.find_all("td")
        if len(cols) >= 4:
            name = cols[1].get_text(strip=True)
            designation = cols[2].get_text(strip=True)
            contact = cols[3].get_text(strip=True)
            if name and designation:
                data.append([name, designation, contact])
# Save to Excel
if data:
    df = pd.DataFrame(data, columns=["Name", "Designation", "Contact"])
    df.to_excel("Civil_Staff.xlsx", index=False)
    print("Saved as Civil_Staff.xlsx")
else:
    print("No data found.")
print("Done.")

Quiz: Which library is used to parse HTML in this program?

BeautifulSoup
openpyxl
smtplib

Automation made Easy!🚶‍➡️

Python Automation Handson Python Automation Handson #1 Toggle Dark Mode ...