File & Media Automation

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 61 of 65 ๐Ÿ“‚ Phase 12: Automation and Professional Skills ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Excel Automation (openpyxl) ยท PDF Manipulation (pypdf) ยท Image Processing (Pillow/PIL) ยท Automated Email Dispatch (smtplib & MIME)
Master multi-format office and media automation in Python: manipulating Excel spreadsheets with openpyxl, extracting text and merging PDFs with pypdf, batch resizing and filtering images with Pillow (PIL), and sending automated rich HTML emails with attachments via smtplib.
1Automated Excel Spreadsheet Processing with openpyxl

Excel is the universal language of business. The openpyxl package allows Python scripts to read, modify, format, apply Excel formulas, and generate automated financial workbooks without installing Microsoft Office.

The openpyxl Hierarchy:

  • Workbook: The entire .xlsx file in memory.
  • Worksheet (Sheet): A specific tab within the workbook (e.g. wb['Q1_Sales']).
  • Cell: An individual coordinate (e.g. sheet['B4'] or sheet.cell(row=4, column=2)) holding values, formulas (=SUM(B2:B10)), and font formatting.
๐Ÿ’ป Example 1: Automated Financial Excel Spreadsheet Generation
# Excel Automation Simulation: Generating an Automated Financial Report
def generate_excel_financial_report(sales_data):
    """Simulates openpyxl workbook creation and formula computation."""
    workbook = {"title": "Q3_Financial_Summary.xlsx", "rows": []}
    
    # 1. Header row:
    headers = ["Transaction ID", "Client Name", "Product", "Gross Amount (INR)", "GST (18%)", "Total Payable"]
    workbook["rows"].append(headers)

    # 2. Populate transaction rows with automated formula calculation:
    for idx, (client, product, gross) in enumerate(sales_data, start=1001):
        gst = round(gross * 0.18, 2)
        total = round(gross + gst, 2)
        workbook["rows"].append([f"INV#{idx}", client, product, f"โ‚น{gross:,.2f}", f"โ‚น{gst:,.2f}", f"โ‚น{total:,.2f}"])

    return workbook

sample_sales = [
    ("TechCorp India", "Cloud Enterprise License", 150000.0),
    ("Apex Dynamics",  "Cybersecurity Audit",       85000.0),
    ("InnovateLabs",   "AI Training Platform",      220000.0)
]

report = generate_excel_financial_report(sample_sales)
print(f"--- ๐Ÿ“Š Automated Excel Workbook Generated: [{report['title']}] ---")
for r in report["rows"]:
    print(f"{r[0]:<10} {r[1]:<18} {r[2]:<26} {r[3]:<16} {r[4]:<12} {r[5]:<14}")
๐Ÿ” Real openpyxl Syntax:

In openpyxl: import openpyxl; wb = openpyxl.Workbook(); ws = wb.active; ws.append(['Name', 'Sales']); ws['B5'] = '=SUM(B2:B4)'; wb.save('report.xlsx').

2PDF Manipulation, Image Processing (Pillow) & Automated Emailing

Python provides mature standard libraries and third-party packages for complete media pipeline automation:

  • PDF Processing (pypdf / pdfplumber): Extract text from contracts, merge multiple PDF files, rotate pages, and encrypt documents with passwords.
  • Image Processing (Pillow / PIL): Batch resize photos, crop banners, apply watermarks, convert PNG to WebP/JPEG, and compress images for web publishing.
  • Email Automation (smtplib & email.mime): Connects to SMTP servers (Gmail, SendGrid, Amazon SES) to send automated transactional HTML emails with PDF invoice attachments.
๐Ÿ’ป Example 2: Automated Transactional Email Dispatcher with PDF Attachment
# Automated Email Dispatch Pipeline Simulation:
import datetime

class AutomatedEmailDispatcher:
    """Simulates sending rich HTML emails with attachments via SMTP."""
    
    def __init__(self, smtp_server="smtp.gmail.com", port=587):
        self.server = smtp_server
        self.port = port

    def send_invoice_email(self, recipient_email, customer_name, invoice_id, amount, attachment_file):
        """Constructs MIME multipart message and sends via SMTP."""
        email_payload = {
            "To": recipient_email,
            "From": "billing@ourcompiler.com",
            "Subject": f"Invoice #{invoice_id} from Our Compiler โ€” Paid Successfully",
            "Date": datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S"),
            "Attachment": attachment_file,
            "HTML_Body": f"""
            
              
                

Dear {customer_name},

Thank you for your business! Your payment of โ‚น{amount:,.2f} has been processed successfully.

Your official tax invoice {attachment_file} is attached to this email.


Best regards,
Our Compiler Billing Team

""" } print(f"๐Ÿ“ง [SMTP DISPATCH] Sent Email to {recipient_email} with attachment: '{attachment_file}'") return email_payload # Run Email Dispatcher Demo: dispatcher = AutomatedEmailDispatcher() res = dispatcher.send_invoice_email( recipient_email="balaji.dev@example.com", customer_name="Balaji", invoice_id="INV-2026-894", amount=1499.00, attachment_file="Invoice_INV-2026-894.pdf" )
๐Ÿ” SMTP Security with TLS:

In production Python, use server = smtplib.SMTP('smtp.gmail.com', 587); server.starttls() to encrypt credentials with Transport Layer Security (TLS) before sending passwords.

โš ๏ธ Common Developer Pitfall: Hardcoding Email Passwords Directly in Scripts

Never write raw email passwords in Python code. When using Gmail, generate an App Password from Google Security settings and load it via os.getenv("EMAIL_APP_PASSWORD").

๐Ÿ’ป Hands-on Interactive Practice Challenge

Write an image thumbnail calculator function get_thumbnail_size(width, height, max_size=300) that maintains the original aspect ratio.

Python 3 Practice Challenge โ–ถ Run in Compiler
def get_thumbnail_size(width, height, max_size=300):
    ratio = min(max_size / width, max_size / height)
    return int(width * ratio), int(height * ratio)

print("Original 1920x1080 -> Thumbnail:", get_thumbnail_size(1920, 1080))
print("Original 800x1200  -> Thumbnail:", get_thumbnail_size(800, 1200))
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

Q Which library is best for extracting tables from PDFs in Python?

pdfplumber is the gold standard for extracting complex tabular data from PDF files, while pypdf is optimal for merging, splitting, and rotating PDF pages.

Q How do I convert an image format from PNG to WebP in Pillow?

Open with img = Image.open("photo.png") and save with img.save("photo.webp", "WEBP", quality=85, optimize=True).

Q What is the difference between openpyxl and Pandas for Excel files?

Pandas (pd.read_excel) is optimized for loading tabular numeric data into DataFrames for analysis. openpyxl is designed for cell-level formatting, styling, charts, and formulas.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026