Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Python Fundamentals Level Two ยท Lesson 6 of 9

Module FIve

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
6
Module Five: Automation and Scripting with Python

๐Ÿ Module Five: Automation and Scripting with Python


๐Ÿ“– Module Introduction

Welcome, future automation engineer! ๐ŸŒŸ You have learned so much in this course โ€” from building web apps with Flask to analysing data with Pandas and creating beautiful visualizations. Now, it is time to learn one of the most powerful and practical uses of Python: automation and scripting.

Imagine you have a task that you do every day โ€” renaming files, sending emails, downloading data, or even filling out forms. Wouldn't it be amazing if a computer could do it for you? That is exactly what automation is all about: teaching computers to do repetitive tasks so you can focus on more important things.

In this module, you will learn how to write Python scripts that automate everyday tasks. You will learn how to work with files and folders, schedule tasks to run automatically, send emails with Python, control web browsers with Selenium, and build your own command-line tools. By the end of this module, you will be able to save hours of time every week by automating boring, repetitive work.

Think of this module as giving you a magic helper ๐Ÿค– that does all the boring stuff for you. Let us begin our automation adventure! ๐Ÿš€


๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what automation is and why it is useful.
  • Work with files and folders using the os and shutil modules.
  • Move, rename, copy, and delete files programmatically.
  • Schedule scripts to run at specific times using the schedule library.
  • Send automated emails using smtplib.
  • Automate web interactions with Selenium.
  • Execute system commands using the subprocess module.
  • Build command-line tools with argparse.
  • Create automated reports from data.
  • Combine all these skills to build a complete automation project.

๐Ÿ“š Warm-up Story: Ada's Automated Assistant

Ada was a busy student who also helped her mother run the family store. Every day, she had to do the same boring tasks: check inventory, update prices, send sales reports to her mother, and organize receipts into folders. It took hours each week!

One day, Ada thought, "Why can't a computer do all this for me?" She remembered learning about automation in Python. She decided to write a script that would do everything automatically.

She wrote a script that used the os module to organize receipts into monthly folders. She used the schedule library to run the script every night. She used smtplib to send an automatic email to her mother with a daily sales summary. She even used Selenium to download the latest price list from the supplier's website.

"Amazing!" her mother said. "Now you have more time to study and play." Ada had built her own automated assistant. And now, you will learn how to build yours! ๐Ÿค–


๐Ÿ“˜ Lesson 1: What is Automation?

Definition: Automation is the process of using technology to perform tasks with minimal human intervention.

Why it is important: Automation saves time, reduces errors, and allows you to focus on more creative and important work.

Simple explanation: Imagine you have to water your plants every day. If you set up an automatic watering system, the plants get watered without you having to remember. That is automation!

Real-life example: A factory uses robots to assemble cars automatically.

School example: You set a reminder on your phone to study at the same time every day.

Home example: A smart thermostat adjusts the temperature automatically.

Nigerian example: A POS machine automatically deducts money from your account when you buy something.

Illustration:

    AUTOMATION CONCEPT
    +-------------------------------------------------+
    |  Human task  โ†’  Automated script  โ†’  Done!      |
    |  (Boring,     (Computer does     (No more       |
    |   repetitive)  it for you)        boring work)  |
    +-------------------------------------------------+
    

Mini summary: Automation uses computers to do repetitive tasks so you do not have to.


๐Ÿ“˜ Lesson 2: Working with Files and Folders โ€“ The os Module

Definition: The os module provides functions for interacting with the operating system โ€” working with files, folders, and system paths.

Why it is important: Many automation tasks involve organizing, renaming, or moving files. The os module makes this easy.

Simple explanation: Imagine you have a messy desk with papers everywhere. The os module is like your hands ๐Ÿ‘‹ that can pick up papers, move them, and put them in folders.

Common functions:

    import os

    # Get current working directory
    current_dir = os.getcwd()
    print(current_dir)

    # List files in a directory
    files = os.listdir('.')
    print(files)

    # Create a new folder
    os.mkdir('new_folder')

    # Check if a file or folder exists
    exists = os.path.exists('file.txt')

    # Rename a file
    os.rename('old.txt', 'new.txt')

    # Remove a file
    os.remove('file.txt')

    # Remove an empty folder
    os.rmdir('empty_folder')

    # Join paths (works on any operating system)
    path = os.path.join('folder', 'subfolder', 'file.txt')
    

Real-life example: A script that organizes downloaded files into folders by type.

School example: You organize your class notes into subject folders.

Home example: You sort your photos into folders by year.

Nigerian example: A business automatically backs up daily sales records to a dated folder.

Illustration:

    OS MODULE FUNCTIONS
    +-------------------------------------------------+
    |  os.getcwd() โ†’ get current folder                |
    |  os.listdir() โ†’ list all files/folders          |
    |  os.mkdir()   โ†’ create a new folder             |
    |  os.rename()  โ†’ rename a file or folder         |
    |  os.remove()  โ†’ delete a file                   |
    +-------------------------------------------------+
    

Mini summary: The os module lets you interact with the file system โ€” create, rename, delete, and check files and folders.


๐Ÿ“˜ Lesson 3: Copying and Moving Files โ€“ The shutil Module

Definition: The shutil module provides high-level operations on files and collections of files, like copying and moving.

Why it is important: Copying and moving files are common tasks in automation (e.g., backing up files, organizing data).

Simple explanation: If os is your hands, shutil is like having a forklift ๐Ÿ—๏ธ โ€” it can handle larger operations like copying entire folders.

Common functions:

    import shutil

    # Copy a file
    shutil.copy('source.txt', 'destination.txt')

    # Copy a file to a different folder (keeps filename)
    shutil.copy('source.txt', 'backup/')

    # Copy an entire folder
    shutil.copytree('original_folder', 'backup_folder')

    # Move a file or folder
    shutil.move('file.txt', 'new_location/')

    # Remove an entire folder (dangerous!)
    shutil.rmtree('folder_to_delete')
    

Real-life example: A script that copies all PDFs from your downloads folder to a "Documents" folder.

School example: You copy a project folder to a USB drive as a backup.

Home example: You move photos from your phone to your computer.

Nigerian example: A business copies daily sales data to a backup drive.

Illustration:

    SHUTIL MODULE FUNCTIONS
    +-------------------------------------------------+
    |  shutil.copy()   โ†’ copy a file                  |
    |  shutil.copytree() โ†’ copy a whole folder        |
    |  shutil.move()   โ†’ move a file or folder        |
    |  shutil.rmtree() โ†’ delete a folder (careful!)   |
    +-------------------------------------------------+
    

Mini summary: shutil lets you copy, move, and delete files and folders at a higher level than os.


๐Ÿ“˜ Lesson 4: Walking Through Folders (os.walk)

Definition: os.walk() is a function that generates the file names in a directory tree by walking either top-down or bottom-up. It is used to go through every folder and file inside a directory.

Why it is important: Many automation tasks require you to process all files in a folder and its subfolders โ€” for example, organizing all images in a messy directory.

Simple explanation: Imagine you are exploring a huge building with many rooms (folders) and each room has items (files). os.walk() helps you visit every room and see every item.

How to use os.walk:

    import os

    # Walk through all folders and files
    for root, dirs, files in os.walk('.'):
        print(f"Folder: {root}")
        print(f"  Subfolders: {dirs}")
        print(f"  Files: {files}")

        # Process each file
        for filename in files:
            filepath = os.path.join(root, filename)
            print(f"  Processing: {filepath}")
    

Real-life example: A script that finds all image files in a folder and all its subfolders.

School example: You search for all PDFs in your schoolwork folder.

Home example: You find all photos on your computer and organize them by date.

Nigerian example: A business scans all folders for receipts and moves them to an archive.

Illustration:

    OS.WALK STRUCTURE
    +-------------------------------------------------+
    |  root/                                          |
    |  โ”œโ”€โ”€ folder1/                                   |
    |  โ”‚   โ”œโ”€โ”€ file1.txt                              |
    |  โ”‚   โ””โ”€โ”€ subfolder/                             |
    |  โ”‚       โ””โ”€โ”€ file2.txt                          |
    |  โ””โ”€โ”€ folder2/                                   |
    |      โ””โ”€โ”€ file3.txt                              |
    +-------------------------------------------------+
    |  os.walk() visits every folder and file         |
    +-------------------------------------------------+
    

Mini summary: os.walk() lets you visit every folder and file in a directory tree, making it easy to process all files.


๐Ÿ“˜ Lesson 5: Scheduling Scripts with the schedule Library

Definition: The schedule library lets you run Python functions at specific times or intervals, like every day at 8 AM or every 10 minutes.

Why it is important: Many automation tasks need to run regularly โ€” daily backups, weekly reports, hourly checks. Scheduling makes this automatic.

Simple explanation: Think of schedule as an alarm clock โฐ for your Python scripts. You tell it when to run your code, and it reminds you (or just runs it).

How to install and use:

    pip install schedule

    import schedule
    import time

    def my_task():
        print("Task is running!")

    # Schedule the task
    schedule.every(10).minutes.do(my_task)
    schedule.every().hour.do(my_task)
    schedule.every().day.at("08:00").do(my_task)
    schedule.every().monday.do(my_task)

    # Keep the script running
    while True:
        schedule.run_pending()
        time.sleep(1)
    

Real-life example: A script that backs up a folder every night at 2 AM.

School example: A reminder to study at the same time every day.

Home example: A script that turns off your computer at a certain time.

Nigerian example: A business runs a sales report every day at 6 PM.

Illustration:

    SCHEDULE LIBRARY
    +-------------------------------------------------+
    |  schedule.every().day.at("08:00").do(task)      |
    |  โ†’ Runs task every day at 8:00 AM               |
    |  schedule.every(10).minutes.do(task)            |
    |  โ†’ Runs task every 10 minutes                   |
    +-------------------------------------------------+
    

Mini summary: The schedule library lets you run Python functions automatically at specified times or intervals.


๐Ÿ“˜ Lesson 6: Sending Emails with smtplib

Definition: smtplib is a Python library that allows you to send emails using the SMTP (Simple Mail Transfer Protocol) protocol.

Why it is important: Sending automated emails is a common automation task โ€” for reports, notifications, alerts, and more.

Simple explanation: Imagine you are a secretary โœ‰๏ธ who sends letters for your boss. smtplib is like a robot secretary that sends emails automatically.

How to send an email:

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    # Email details
    sender = "your_email@gmail.com"
    password = "your_app_password"  # Use App Password for Gmail
    receiver = "friend@example.com"
    subject = "Automated Email"
    body = "This email was sent automatically by a Python script!"

    # Create message
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    # Send email
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender, password)
        server.send_message(msg)
        server.quit()
        print("Email sent successfully!")
    except Exception as e:
        print(f"Error: {e}")
    

Real-life example: A script that sends a daily sales report to the manager.

School example: A script that sends a reminder email before a deadline.

Home example: A script that emails your family the weekly shopping list.

Nigerian example: A business sends automated invoices to customers.

Illustration:

    SENDING EMAILS
    +-------------------------------------------------+
    |  smtplib โ†’ connect to email server              |
    |  โ†“                                              |
    |  Login with your email and password             |
    |  โ†“                                              |
    |  Compose the email (subject, body, recipient)   |
    |  โ†“                                              |
    |  Send the email                                 |
    +-------------------------------------------------+
    

Mini summary: smtplib lets you send automated emails from your Python scripts. You need an email account and server settings.


๐Ÿ“˜ Lesson 7: Web Automation with Selenium

Definition: Selenium is a tool that automates web browsers. It can click buttons, fill forms, and extract data from websites just like a human would.

Why it is important: Some websites do not provide APIs (like we learned in earlier modules). Selenium lets you interact with websites that require clicking, logging in, or JavaScript.

Simple explanation: Imagine you have a robot ๐Ÿค– that can use a web browser just like you โ€” clicking, typing, and reading. That is Selenium.

How to install and use Selenium:

    pip install selenium

    # Download the Chrome WebDriver from chromedriver.chromium.org
    # and put it in your PATH.

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

    # Launch browser
    driver = webdriver.Chrome()

    # Go to a website
    driver.get("https://example.com")

    # Find an element by ID, class, or tag
    element = driver.find_element(By.ID, "search-box")
    element.send_keys("Python automation")

    # Click a button
    button = driver.find_element(By.CLASS_NAME, "search-button")
    button.click()

    # Wait for page to load
    time.sleep(2)

    # Get page title
    title = driver.title
    print(title)

    # Close the browser
    driver.quit()
    

Real-life example: A script that automatically logs in to a website and downloads a report.

School example: A script that checks your school portal for new grades and notifies you.

Home example: A script that checks if a product is in stock on a shopping website.

Nigerian example: A script that checks JAMB admission status automatically.

Illustration:

    SELENIUM WORKFLOW
    +-------------------------------------------------+
    |  Launch browser                                 |
    |  โ†“                                              |
    |  Go to website                                  |
    |  โ†“                                              |
    |  Find elements (by ID, class, etc.)             |
    |  โ†“                                              |
    |  Interact (type text, click, etc.)             |
    |  โ†“                                              |
    |  Extract data or take screenshot               |
    |  โ†“                                              |
    |  Close browser                                  |
    +-------------------------------------------------+
    

Mini summary: Selenium automates web browsers. It can click, type, and extract data from websites that need human interaction.


๐Ÿ“˜ Lesson 8: Running System Commands with subprocess

Definition: The subprocess module lets you run system commands from Python โ€” like dir on Windows, ls on Linux, or any program you can run from the terminal.

Why it is important: Sometimes you need to run external programs from your Python script โ€” compressing files, converting images, or using command-line tools.

Simple explanation: Imagine you are a conductor ๐ŸŽถ who tells other instruments (programs) what to play. subprocess lets you conduct other programs from your Python script.

How to use subprocess:

    import subprocess

    # Run a command and get the output
    result = subprocess.run(['ls', '-la'], capture_output=True, text=True)
    print(result.stdout)

    # Run a command (simple)
    subprocess.run(['mkdir', 'new_folder'])

    # Run a command and check if it succeeded
    result = subprocess.run(['ping', '-c', '4', 'google.com'], capture_output=True, text=True)
    if result.returncode == 0:
        print("Ping successful!")
    else:
        print("Ping failed.")
    

Real-life example: A script that compresses files using zip command after processing.

School example: A script that runs a program to convert documents to PDF.

Home example: A script that backs up files using the rsync command.

Nigerian example: A script that runs a database backup command.

Illustration:

    SUBPROCESS WORKFLOW
    +-------------------------------------------------+
    |  Python script                                  |
    |  โ†“                                              |
    |  subprocess.run(['command', 'arg1', 'arg2'])    |
    |  โ†“                                              |
    |  System runs the command                        |
    |  โ†“                                              |
    |  Results are returned to Python                 |
    +-------------------------------------------------+
    

Mini summary: subprocess lets you run system commands from Python, giving you access to any program on your computer.


๐Ÿ“˜ Lesson 9: Building Command-Line Tools with argparse

Definition: argparse is a module that helps you build command-line interfaces for your Python scripts. It handles arguments, options, and help messages.

Why it is important: Command-line tools are powerful and user-friendly. They let users interact with your script by typing commands like python script.py --input file.txt --output result.csv.

Simple explanation: Imagine you have a magic wand ๐Ÿช„ that works differently depending on what you say. argparse is like the instruction manual that tells people how to use your magic wand (your script).

How to use argparse:

    import argparse

    # Create a parser
    parser = argparse.ArgumentParser(description='A simple file processor.')

    # Add arguments
    parser.add_argument('input_file', help='The input file to process')
    parser.add_argument('-o', '--output', help='Output file name', default='output.txt')
    parser.add_argument('-v', '--verbose', action='store_true', help='Print verbose output')
    parser.add_argument('--count', type=int, default=1, help='Number of times to process')

    # Parse arguments
    args = parser.parse_args()

    # Use the arguments
    print(f"Processing: {args.input_file}")
    print(f"Output file: {args.output}")
    if args.verbose:
        print(f"Verbose mode is ON")
    print(f"Count: {args.count}")

    # Main logic here...
    

Running the script:

    python script.py data.txt -o results.csv -v --count 5
    

Real-life example: A data processing script that takes input file, output format, and processing options.

School example: A script that analyses test scores and takes a file name and options for output.

Home example: A script that organises photos with options for destination folder and date filter.

Nigerian example: A currency converter script that takes amount and currencies as arguments.

Illustration:

    ARGPARSE USAGE
    +-------------------------------------------------+
    |  python script.py --help                         |
    |  โ†’ shows help message                           |
    |  python script.py input.csv -o output.json      |
    |  โ†’ processes input.csv and saves output.json    |
    +-------------------------------------------------+
    

Mini summary: argparse helps you build professional command-line tools with arguments, options, and help messages.


๐Ÿ“˜ Lesson 10: Putting It All Together โ€“ A Complete Automation App

Now we will build a complete automation application that combines all the skills we have learned.

Scenario: We will build a "Daily Report Generator" that:

  • Scans a folder for data files.
  • Processes the data (using Pandas).
  • Creates a chart (using Matplotlib).
  • Sends an email report (using smtplib).
  • Schedules itself to run daily (using schedule).
  • Uses command-line arguments for configuration (using argparse).

Code (simplified):

    import os
    import pandas as pd
    import matplotlib.pyplot as plt
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    import schedule
    import time
    import argparse

    def process_data(folder):
        """Find the latest data file and process it."""
        files = os.listdir(folder)
        csv_files = [f for f in files if f.endswith('.csv')]
        if not csv_files:
            print("No CSV files found.")
            return None
        latest = max(csv_files, key=lambda f: os.path.getmtime(os.path.join(folder, f)))
        df = pd.read_csv(os.path.join(folder, latest))
        return df

    def create_chart(df, output_file):
        """Create a chart from the data."""
        plt.figure(figsize=(10, 6))
        df.plot(kind='bar')
        plt.title('Daily Report')
        plt.tight_layout()
        plt.savefig(output_file)
        plt.close()

    def send_report(email, password, recipient, subject, body, chart_file):
        """Send an email with the report and chart."""
        msg = MIMEMultipart()
        msg['From'] = email
        msg['To'] = recipient
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        with open(chart_file, 'rb') as f:
            img = MIMEImage(f.read())
            img.add_header('Content-Disposition', 'attachment', filename=chart_file)
            msg.attach(img)

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(email, password)
        server.send_message(msg)
        server.quit()
        print("Report sent!")

    def run_daily_report(folder, email, password, recipient):
        """Run the complete daily report process."""
        print("Generating daily report...")
        df = process_data(folder)
        if df is None:
            return

        chart_file = 'daily_report.png'
        create_chart(df, chart_file)

        send_report(email, password, recipient, 'Daily Report', 'Please find the daily report attached.', chart_file)

        print("Daily report complete.")

    def main():
        parser = argparse.ArgumentParser(description='Daily Report Generator')
        parser.add_argument('folder', help='Folder containing data files')
        parser.add_argument('--email', required=True, help='Sender email')
        parser.add_argument('--password', required=True, help='Email password')
        parser.add_argument('--recipient', required=True, help='Recipient email')
        args = parser.parse_args()

        # Schedule the report every day at 8 AM
        schedule.every().day.at("08:00").do(run_daily_report, args.folder, args.email, args.password, args.recipient)

        print("Report generator started. Running daily at 8 AM.")
        while True:
            schedule.run_pending()
            time.sleep(60)

    if __name__ == "__main__":
        main()
    

What we used:

  • os module for file operations
  • Pandas for data processing
  • Matplotlib for chart creation
  • smtplib for sending emails
  • schedule for scheduling
  • argparse for command-line arguments

Illustration:

    DAILY REPORT GENERATOR FLOW
    +-------------------------------------------------+
    |  1. Scan folder for CSV files                   |
    |  2. Process data with Pandas                    |
    |  3. Create chart with Matplotlib                |
    |  4. Send email with chart attached              |
    |  5. Schedule to run daily at 8 AM              |
    +-------------------------------------------------+
    

Mini summary: The complete automation app combines file operations, data processing, visualization, email, scheduling, and command-line arguments into a powerful, automated tool.


๐Ÿ“– Key Vocabulary

Word Simple Definition
Automation Using computers to do repetitive tasks for you.
Script A program written to automate a specific task.
os Module A Python module for working with files and folders.
shutil Module A Python module for copying and moving files.
os.walk() A function that visits every folder and file in a directory.
schedule A library for scheduling tasks to run at specific times.
smtplib A library for sending emails from Python.
Selenium A tool for automating web browsers.
subprocess A module for running system commands from Python.
argparse A module for building command-line tools.

โญ Important Concepts

  • Automation saves time and reduces errors by letting computers do repetitive tasks.
  • The os and shutil modules let you work with files and folders programmatically.
  • os.walk() is essential for processing all files in a directory tree.
  • Schedule lets you run scripts at specific times automatically.
  • smtplib allows you to send automated emails.
  • Selenium automates web browsers for tasks that require clicking and typing.
  • subprocess lets you run any system command from Python.
  • argparse helps you build professional command-line tools.
  • Combining these tools lets you build powerful automation systems.

๐Ÿ”ง Step-by-Step Explanations

๐Ÿ”น How to Organize Files with Python

  1. Use os.listdir() to get all files in a folder.
  2. Loop through the files and check the file extension.
  3. Create destination folders if they don't exist (os.mkdir()).
  4. Use shutil.move() to move files to the right folder.
  5. Use os.walk() if you need to go into subfolders.

๐Ÿ”น How to Schedule a Task

  1. Install the schedule library: pip install schedule.
  2. Define a function that does the task.
  3. Schedule the function using schedule.every().
  4. Create an infinite loop that calls schedule.run_pending().
  5. Add a time.sleep() to avoid using too much CPU.

๐Ÿ”น How to Build a Command-Line Tool

  1. Import argparse.
  2. Create a parser with argparse.ArgumentParser().
  3. Add arguments with add_argument().
  4. Parse arguments with parser.parse_args().
  5. Use the arguments in your script.
  6. Test by running the script with different options.

๐ŸŒ Real-life Examples

  • File organizer: A script that automatically sorts files in your Downloads folder by type.
  • Email automation: A script that sends weekly newsletters to subscribers.
  • Data backup: A scheduled script that backs up important files to the cloud.
  • Web scraping: A script that checks a website for updates and sends alerts.
  • Report generation: A script that creates and emails daily reports automatically.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Market price tracker: A script that scrapes prices from different markets and sends alerts.
  • School result notification: A script that checks your school portal and emails you when results are posted.
  • Business inventory: A script that automatically generates inventory reports and emails them to the owner.
  • Agricultural monitoring: A script that checks weather data and sends alerts to farmers.
  • Banking automation: A script that automatically downloads and organizes bank statements.

๐ŸŽˆ Fun Examples Children Can Relate To

  • Homework organizer: A script that organizes school files into subject folders.
  • Game score notifier: A script that checks if you got a new high score and sends an email.
  • TV show reminder: A script that reminds you when your favourite show is about to start.
  • Chore tracker: A script that sends a reminder to do your chores.
  • Birthday bot: A script that sends birthday wishes to your friends automatically.

๐Ÿ  Everyday Examples

  • Budget tracker: A script that automatically categorises expenses from a CSV file.
  • Photo organizer: A script that sorts photos by date into folders.
  • To-do list: A script that sends a daily email with your tasks for the day.
  • File cleaner: A script that deletes temporary files older than a certain date.
  • Reading log: A script that tracks the number of pages read per day and sends a summary.

๐Ÿ‘ฉโ€๐Ÿซ Teacher Notes

  • Start with practical examples: Show students how automation can help in their daily lives.
  • Encourage creativity: Let students think of something they want to automate.
  • Hands-on practice: Have students write scripts to organize files, send emails, or schedule tasks.
  • Discuss Selenium: Demonstrate how it works with a live website.
  • Safety first: Warn about the dangers of shutil.rmtree() and deleting files accidentally.
  • Command-line tools: Show how argparse makes scripts more professional.

๐Ÿ‘ช Parent Tips

  • Encourage automation thinking: Ask your child "What boring task would you like to automate?"
  • Provide a safe environment: Let them practice on a test folder, not important files.
  • Celebrate creations: When they build an automation script, let them show you how it works.
  • Discuss security: Talk about why we use app passwords and keep them secret.
  • Explore together: Help them think of useful things to automate in your home or business.

๐Ÿค” Interesting Facts

  • The first industrial robot was installed in 1961 and was used for die-casting.
  • Selenium was originally developed to automate web testing and is now used for many other automation tasks.
  • Python is one of the most popular languages for automation because it is easy to learn and has many libraries.
  • Automated emails have been used since the early days of the internet.
  • The term "robot" comes from the Czech word "robota," which means "forced labor."

๐Ÿ’ก Did You Know?

  • Did you know? You can use Selenium to take screenshots of websites automatically.
  • Did you know? The schedule library can handle timezones using the pytz module.
  • Did you know? You can use subprocess to run other Python scripts from your script.
  • Did you know? You can send emails with attachments (like images, PDFs) using smtplib and email.mime.
  • Did you know? os.walk() can be used to find and delete duplicate files.
  • Did you know? You can use Selenium to automate social media posting.

๐Ÿง  Remember This

  • Automation lets computers do repetitive tasks for you.
  • Use os and shutil for working with files and folders.
  • os.walk() visits every folder and file in a directory.
  • schedule runs tasks at specific times.
  • smtplib sends automated emails.
  • Selenium automates web browsers.
  • subprocess runs system commands from Python.
  • argparse builds command-line tools.
  • Always test automation scripts on safe data first.

โš ๏ธ Common Mistakes

Mistake How to Avoid It
Deleting the wrong file or folder Always test on copies first. Use os.path.exists() to check.
Using shutil.rmtree() without checking Double-check the path before deleting.
Forgetting to add schedule.run_pending() in the loop Always include the infinite loop with schedule.run_pending().
Hardcoding email passwords in scripts Use environment variables or a config file.
Not handling exceptions in Selenium Use try-except to handle element not found errors.
Using subprocess.run() without capture_output=True Use capture_output=True to capture output and errors.
Not using text=True with subprocess Use text=True to get string output instead of bytes.

โœ… Best Practices

  • Always test on a safe copy when deleting or moving files.
  • Use environment variables for sensitive data like email passwords.
  • Add error handling to your automation scripts.
  • Log your actions so you can track what the script did.
  • Use meaningful variable names in your scripts.
  • Add comments to explain what each part of the script does.
  • Use argparse to make your scripts user-friendly.
  • Schedule tasks to run during off-peak hours if possible.
  • Keep your scripts modular โ€” break them into functions.

๐Ÿ–ผ๏ธ Diagrams and Illustrations

File Organization Flow

    FILE ORGANIZATION FLOW
    +-------------------------------------------------+
    |  Start                                           |
    |  โ†“                                              |
    |  List files in folder                           |
    |  โ†“                                              |
    |  For each file, check extension                 |
    |  โ†“                                              |
    |  Move to appropriate subfolder                  |
    |  โ†“                                              |
    |  Done!                                          |
    +-------------------------------------------------+
    

Scheduling Flow

    SCHEDULING FLOW
    +-------------------------------------------------+
    |  schedule task                                  |
    |  โ†“                                              |
    |  While True:                                    |
    |  โ†“                                              |
    |  Check pending tasks                            |
    |  โ†“                                              |
    |  If task is due, run it                         |
    |  โ†“                                              |
    |  Wait 1 second                                  |
    +-------------------------------------------------+
    

Daily Report Generator Flow

    DAILY REPORT GENERATOR
    +-------------------------------------------------+
    |  1. Scan folder for latest CSV                  |
    |  2. Process data with Pandas                    |
    |  3. Create chart                               |
    |  4. Send email with attachment                  |
    |  5. Schedule for next day                      |
    +-------------------------------------------------+
    

Selenium Web Automation

    SELENIUM FLOW
    +-------------------------------------------------+
    |  Launch browser                                 |
    |  โ†“                                              |
    |  Navigate to URL                                |
    |  โ†“                                              |
    |  Find elements (ID, class, XPath)              |
    |  โ†“                                              |
    |  Interact (click, type, submit)                |
    |  โ†“                                              |
    |  Extract data / take screenshot                 |
    |  โ†“                                              |
    |  Close browser                                  |
    +-------------------------------------------------+
    

๐Ÿ“Š Comparison Tables

Comparison: os vs shutil

Feature os Module shutil Module
Rename files Yes (os.rename()) No
Copy files No Yes (shutil.copy())
Move files Yes (os.rename()) Yes (shutil.move())
Copy entire folders No Yes (shutil.copytree())
Delete files Yes (os.remove()) No
Delete folders Yes (os.rmdir() empty only) Yes (shutil.rmtree() full)

Comparison: Selenium vs requests

Feature requests Selenium
Speed Fast (raw HTTP) Slower (browser automation)
JavaScript execution No Yes
Interactions (click, type) No Yes
Resources Low High (browser overhead)
Use case APIs, static pages Dynamic pages, user interactions

Lesson 1 Summary: Automation uses computers to do repetitive tasks for you.

Lesson 2 Summary: The os module works with files and folders (rename, delete, check existence).

Lesson 3 Summary: shutil copies and moves files and whole folders.

Lesson 4 Summary: os.walk() visits every folder and file in a directory tree.

Lesson 5 Summary: The schedule library runs functions at specific times.

Lesson 6 Summary: smtplib sends automated emails.

Lesson 7 Summary: Selenium automates web browsers (click, type, extract).

Lesson 8 Summary: subprocess runs system commands from Python.

Lesson 9 Summary: argparse builds command-line tools with arguments and options.

Lesson 10 Summary: Combining all tools creates powerful automation systems.


๐Ÿ“ End-of-Module Summary

Congratulations! You have completed Module Five ๐ŸŽ‰. You have learned how to automate tasks with Python, making you more productive and efficient.

You learned how to work with files and folders using the os and shutil modules. You discovered how to schedule tasks to run automatically with the schedule library. You learned how to send automated emails with smtplib, and how to control web browsers with Selenium.

You also learned how to run system commands with subprocess and build professional command-line tools with argparse. You built a complete daily report generator that combines all these skills.

Automation is a superpower. It allows you to save hours of time and eliminate boring, repetitive work. These skills are highly valued in the workplace and can make you a much more effective developer.

In the next module, you will learn about Building RESTful APIs โ€” how to create your own web services that other programs can use.

Keep automating, keep exploring, and never stop learning. You are now an automation engineer! ๐Ÿค–


โ“ Frequently Asked Questions

  1. Q: Is automation only for programmers?
    A: No! While knowing Python helps, there are many no-code automation tools as well. But with Python, you have much more power and flexibility.
  2. Q: Can I automate anything?
    A: Almost anything that is repetitive and rule-based can be automated. But some tasks require human judgement.
  3. Q: Is Selenium better than BeautifulSoup for web scraping?
    A: BeautifulSoup is faster and simpler for static pages. Selenium is better for dynamic pages that need interaction.
  4. Q: How do I keep my email password safe in a script?
    A: Use environment variables or a separate config file. Never hardcode passwords.
  5. Q: Can I schedule scripts on Windows, Mac, and Linux?
    A: Yes! The schedule library works on all platforms. You can also use system-specific schedulers like Task Scheduler or cron.
  6. Q: What if my script runs while I'm using the computer?
    A: Most automation scripts run in the background. Selenium will open a browser, which you might see, but you can run it in headless mode (without a visible browser).
  7. Q: How can I test my automation scripts safely?
    A: Use a test folder with sample files. Never test on important data first. Use print() statements to see what the script would do before actually doing it.
  8. Q: Can I use Python to automate other applications?
    A: Yes! You can use pyautogui to control the mouse and keyboard, or win32com to automate Microsoft Office.
  9. Q: What is the difference between os.rename() and shutil.move()?
    A: os.rename() can only rename or move within the same file system. shutil.move() can move across file systems and is more flexible.
  10. Q: What is the next step after learning automation?
    A: You can learn about building RESTful APIs (Module 6) or explore more advanced topics like machine learning or cloud automation.

๐Ÿ“ Review Questions

  1. What is automation and why is it useful?
  2. What is the difference between the os and shutil modules?
  3. How do you rename a file using Python?
  4. What does os.walk() do?
  5. How do you schedule a task to run at a specific time?
  6. What library is used to send emails in Python?
  7. What is Selenium and when would you use it?
  8. How do you run a system command from Python?
  9. What is the purpose of the argparse module?
  10. How do you copy a file to a different location?
  11. Why should you avoid hardcoding passwords in scripts?
  12. What is the difference between os.remove() and shutil.rmtree()?
  13. How do you check if a file exists before deleting it?
  14. What is the daily report generator an example of?
  15. What is one safety tip for automation scripts?

โœ๏ธ Fill-in-the-Blank Exercises

  1. __________ is the process of using computers to do repetitive tasks.
  2. The __________ module is used for working with files and folders.
  3. The __________ module is used for copying and moving files.
  4. __________ visits every folder and file in a directory tree.
  5. The __________ library is used to schedule tasks in Python.
  6. __________ is used to send emails in Python.
  7. __________ automates web browsers for interaction and scraping.
  8. The __________ module runs system commands from Python.
  9. __________ is used to build command-line tools.
  10. The daily report generator combines file operations, data processing, __________, email, scheduling, and command-line arguments.

โœ… True or False Exercises

  1. Automation can save time and reduce errors. (True / False)
  2. The os module can copy files. (True / False)
  3. shutil.move() can move files and folders. (True / False)
  4. os.walk() only visits the top-level folder. (True / False)
  5. The schedule library runs tasks at specific times. (True / False)
  6. smtplib is used for web automation. (True / False)
  7. Selenium can click buttons and fill forms. (True / False)
  8. subprocess can run system commands. (True / False)
  9. argparse is used for scheduling tasks. (True / False)
  10. You should always test automation scripts on safe data first. (True / False)

๐Ÿ”˜ Multiple Choice Questions

  1. Which module is used for working with files and folders?
    a) sys
    b) os
    c) subprocess
    d) argparse
    Answer: b)
  2. Which module is used for copying and moving files?
    a) os
    b) shutil
    c) sys
    d) subprocess
    Answer: b)
  3. What does os.walk() do?
    a) Deletes all files
    b) Visits every folder and file in a directory
    c) Copies all files
    d) Renames all files
    Answer: b)
  4. Which library is used to schedule tasks?
    a) time
    b) schedule
    c) datetime
    d) calendar
    Answer: b)
  5. Which library is used to send emails in Python?
    a) email
    b) smtplib
    c) sendmail
    d) mail
    Answer: b)
  6. Which tool automates web browsers?
    a) BeautifulSoup
    b) requests
    c) Selenium
    d) urllib
    Answer: c)
  7. Which module runs system commands from Python?
    a) os
    b) shutil
    c) subprocess
    d) sys
    Answer: c)
  8. Which module is used to build command-line tools?
    a) sys
    b) argparse
    c) getopt
    d) optparse
    Answer: b)
  9. Which function copies a file in shutil?
    a) shutil.move()
    b) shutil.copy()
    c) shutil.copyfile()
    d) shutil.copytree()
    Answer: b)
  10. Which function deletes a folder and all its contents?
    a) os.remove()
    b) os.rmdir()
    c) shutil.rmtree()
    d) shutil.delete()
    Answer: c)
  11. How do you check if a file exists?
    a) os.exists()
    b) os.path.exists()
    c) os.check()
    d) os.file_exists()
    Answer: b)
  12. What is the daily report generator an example of?
    a) A simple script
    b) A complete automation system
    c) A web application
    d) A data analysis tool
    Answer: b)
  13. Which of the following is a safety tip for automation?
    a) Always test on important data first
    b) Never test your scripts
    c) Test on safe copies first
    d) Delete files without checking
    Answer: c)
  14. What is the purpose of argparse?
    a) To schedule tasks
    b) To send emails
    c) To parse command-line arguments
    d) To automate web browsers
    Answer: c)
  15. Which library is best for scraping static web pages?
    a) Selenium
    b) BeautifulSoup
    c) requests
    d) Both b and c
    Answer: d) (BeautifulSoup with requests)

๐Ÿ”— Matching Exercises

Match the term on the left with its description on the right:

Term Description
1. os module A. Copies and moves files
2. shutil module B. Sends emails
3. os.walk() C. Works with files and folders
4. schedule D. Visits every folder and file
5. smtplib E. Schedules tasks
6. Selenium F. Runs system commands
7. subprocess G. Automates web browsers
8. argparse H. Builds command-line tools

Answers: 1-C, 2-A, 3-D, 4-E, 5-B, 6-G, 7-F, 8-H


๐Ÿ“ Short Answer Questions

  1. Explain what automation is and give two examples of how it can be used.
  2. What is the difference between the os and shutil modules?
  3. How do you schedule a Python script to run every day at 8 AM?
  4. What is Selenium and when would you use it instead of requests?
  5. How do you run a system command from Python and capture its output?
  6. Why is it important to test automation scripts on safe data?
  7. How do you build a command-line tool with argparse?
  8. What is the daily report generator an example of?
  9. What is the difference between os.remove() and shutil.rmtree()?
  10. What is one best practice for writing automation scripts?

๐ŸŽญ Scenario-based Exercises

Scenario 1:

Ada downloads many files from the internet every day. They all go to her Downloads folder, which becomes messy. She wants to automatically organize files into folders based on their file extension (images, documents, PDFs, etc.) every hour. Write the Python script for this.

Scenario 2:

Chidi wants to send an automated email to his team every Monday morning with a summary of the previous week's tasks. He has a list of tasks in a CSV file. Write the script that reads the CSV and sends the email.

Scenario 3:

Zainab wants to create a command-line tool that takes a folder path and an optional output file, then lists all files in that folder and saves the list to the output file. Write the script using argparse.


๐Ÿ‘ฅ Group Activity

Activity Title: Build an Automated File Organizer

Instructions:

  1. Divide the class into groups of 3โ€“4 students.
  2. Each group will build a file organizer that:
    • Scans a folder (provided as a command-line argument).
    • Categorizes files by extension (images, documents, videos, etc.).
    • Moves each file to the appropriate subfolder.
    • Creates subfolders if they don't exist.
    • Uses os and shutil modules.
    • Uses argparse for command-line options.
    • Includes error handling for common issues.
  3. Each group presents their solution and explains how they handled different file types and errors.

๐Ÿง‘โ€๐ŸŽ“ Individual Activity

Activity Title: Build a Personal Automation Script

Instructions:

  1. Think of a repetitive task you do regularly (organizing files, sending reminders, checking a website, etc.).
  2. Write a Python script that automates this task.
  3. Your script should use at least two of the following: os, shutil, schedule, smtplib, Selenium, subprocess, or argparse.
  4. Submit your script and a short explanation of what it does.

๐Ÿ’ฌ Classroom Discussion Questions

  1. What are the ethical considerations of automation?
  2. How can automation impact jobs and employment?
  3. What are the limitations of automation?
  4. How can automation be used to improve education?
  5. What are the security risks of automation?
  6. What is the most interesting thing you learned about automation?
  7. What would you like to automate in your daily life?

๐Ÿ› ๏ธ Mini Project

Project Title: Build an Automated Email Report System

Description:

Create a complete automated email report system that:

  • Reads data from a CSV file (e.g., sales data).
  • Generates a summary report (using Pandas).
  • Creates a chart (using Matplotlib).
  • Composes an HTML email with the summary and chart attached.
  • Sends the email to a recipient using smtplib.
  • Is scheduled to run weekly using the schedule library.
  • Uses argparse to accept configuration options.
  • Uses a config file or environment variables for sensitive data.

This project will test your ability to combine automation, data analysis, and email into a single system.


๐Ÿ’ป Practical Assignment

Assignment Title: Build a File Backup System

Instructions:

  1. Write a script that:
    • Takes a source folder and a destination folder as arguments.
    • Copies all files from the source to the destination (using shutil).
    • Creates a date-stamped subfolder in the destination.
    • Logs all actions (what was copied, timestamps).
    • Uses argparse for command-line arguments.
    • Includes error handling (e.g., destination not writable).
  2. Schedule the script to run daily at 2 AM using the schedule library.
  3. Submit your script and the log file.

๐Ÿ† Challenge Exercise

Challenge Title: Build a Comprehensive Automation System

Build a comprehensive automation system that monitors a folder, processes new files, and sends notifications. The system should:

  • Monitor a folder for new files (using watchdog library).
  • When a new file appears, identify its type (image, CSV, text, etc.).
  • Process the file appropriately (e.g., compress images, summarize CSV data).
  • Move the processed file to a different folder.
  • Send an email notification about the processed file.
  • Log all activities to a log file.
  • Run continuously as a service.

This challenge combines file monitoring, processing, email, and logging into a complete automation solution. Good luck!


๐Ÿ“ Quiz Answers

Fill-in-the-Blank Answers:

  1. Automation
  2. os
  3. shutil
  4. os.walk()
  5. schedule
  6. smtplib
  7. Selenium
  8. subprocess
  9. argparse
  10. visualization

True or False Answers:

  1. True
  2. False
  3. True
  4. False
  5. True
  6. False
  7. True
  8. True
  9. False
  10. True

Multiple Choice Answers:

  1. b
  2. b
  3. b
  4. b
  5. b
  6. c
  7. c
  8. b
  9. b
  10. c
  11. b
  12. b
  13. c
  14. c
  15. d

๐Ÿ”‘ Key Takeaways

  • Automation saves time and reduces errors by letting computers do repetitive tasks.
  • The os and shutil modules are essential for working with files and folders.
  • os.walk() is the key to processing all files in a directory tree.
  • The schedule library lets you run tasks at specific times.
  • smtplib allows you to send automated emails.
  • Selenium automates web browsers for tasks that require user interaction.
  • subprocess gives you access to any system command from Python.
  • argparse helps you build professional command-line tools.
  • Combining these tools allows you to build powerful automation systems.
  • Safety is important โ€” always test on safe data first.

๐Ÿš€ Preparation for the Next Module

Excellent work completing Module Five! ๐ŸŽ‰ You have learned how to automate tasks with Python, making you a more productive and efficient developer. In the next module, you will learn:

  • Building RESTful APIs โ€” creating web services that other programs can use.
  • Flask-RESTful โ€” an extension for building APIs with Flask.
  • API Endpoints โ€” creating routes that return JSON data.
  • CRUD APIs โ€” creating, reading, updating, and deleting data via API.
  • Authentication โ€” protecting your API with tokens.
  • API Documentation โ€” making your API easy to use.
  • Deploying APIs โ€” putting your API online.

To prepare, review the Flask basics from Level One and the database concepts from earlier. The more you practice, the easier it will be to build powerful APIs.

Keep coding, keep automating, and never stop learning. See you in the next module! ๐Ÿ๐Ÿค–


๐ŸŽ‰ End of Module Five โ€“ Python Fundamentals Level Two ๐ŸŽ‰

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’