Unit 9 • Lesson 8

Basic Automation with Python

Overview

Python can automate repetitive tasks like renaming files, cleaning data, or sending emails. You'll write short scripts that save time by automating everyday digital chores and workflows, making your daily tasks more efficient.

Intermediate 25–30 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • What automation is: Using code to perform repetitive tasks.
  • File automation: Renaming, organizing, and processing files.
  • Data automation: Processing and cleaning data automatically.
  • Task automation: Automating everyday workflows.
  • Benefits: Saving time and reducing errors.

What Is Automation?

Automation is using code to perform repetitive tasks automatically. Instead of doing something manually many times, you write a script to do it for you.

Why Automate?

  • Saves time on repetitive tasks
  • Reduces human errors
  • Works 24/7 without breaks
  • Handles large volumes of work
  • Provides consistent results
Example: Renaming Files
import os

# Rename all files in a directory
for filename in os.listdir('.'):
    if filename.endswith('.txt'):
        new_name = filename.replace('old_', 'new_')
        os.rename(filename, new_name)
        print(f"Renamed {filename} to {new_name}")

File Automation Examples

Automate file operations to save time:

Organizing Files by Extension
import os
import shutil
from pathlib import Path

def organize_files(directory):
    """Organize files into folders by extension"""
    for filename in os.listdir(directory):
        file_path = Path(directory) / filename
        
        if file_path.is_file():
            # Get file extension
            extension = file_path.suffix[1:]  # Remove the dot
            
            # Create folder for extension if it doesn't exist
            folder_path = Path(directory) / extension
            folder_path.mkdir(exist_ok=True)
            
            # Move file to appropriate folder
            shutil.move(str(file_path), str(folder_path / filename))
            print(f"Moved {filename} to {extension}/ folder")

organize_files('.')
Batch Renaming Files
import os
from pathlib import Path

def rename_files(directory, prefix='photo_'):
    """Rename all files in a directory with a prefix"""
    files = [f for f in os.listdir(directory) 
             if os.path.isfile(os.path.join(directory, f))]
    
    for i, filename in enumerate(files, start=1):
        file_path = Path(directory) / filename
        extension = file_path.suffix
        new_name = f"{prefix}{i:03d}{extension}"
        new_path = Path(directory) / new_name
        
        os.rename(file_path, new_path)
        print(f"Renamed {filename} to {new_name}")

rename_files('.', prefix='document_')

Data Processing Automation

Automate data cleaning and processing:

Cleaning CSV Data
import csv

def clean_csv(input_file, output_file):
    """Remove empty rows and clean data"""
    cleaned_rows = []
    
    with open(input_file, 'r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            # Skip empty rows
            if any(cell.strip() for cell in row):
                # Clean whitespace from each cell
                cleaned_row = [cell.strip() for cell in row]
                cleaned_rows.append(cleaned_row)
    
    # Write cleaned data
    with open(output_file, 'w', newline='') as outfile:
        writer = csv.writer(outfile)
        writer.writerows(cleaned_rows)
    
    print(f"Cleaned {len(cleaned_rows)} rows")

clean_csv('data.csv', 'cleaned_data.csv')

Common Automation Tasks

Examples of tasks you can automate:

1

File Organization

Sort files by type, date, or name automatically

2

Data Processing

Clean, transform, and analyze data in batches

3

Email Sending

Send automated reports or notifications

4

Web Scraping

Collect data from websites automatically

5

Backup Tasks

Automatically backup files and folders

6

Report Generation

Create and send reports automatically

Automation Best Practices

Follow these guidelines when automating tasks:

Best Practices

  • Test first: Test your script on a small sample before running on all files
  • Backup data: Always backup important data before automating changes
  • Error handling: Use try/except blocks to handle errors gracefully
  • Logging: Log what your script does for debugging
  • Dry run: Add a "dry run" mode to preview changes without making them
  • Documentation: Document what your script does and how to use it
Safe Automation with Error Handling
import os
from pathlib import Path

def safe_rename_files(directory, prefix='new_', dry_run=True):
    """Safely rename files with error handling"""
    files = [f for f in os.listdir(directory) 
             if os.path.isfile(os.path.join(directory, f))]
    
    for i, filename in enumerate(files, start=1):
        try:
            file_path = Path(directory) / filename
            extension = file_path.suffix
            new_name = f"{prefix}{i:03d}{extension}"
            new_path = Path(directory) / new_name
            
            if dry_run:
                print(f"[DRY RUN] Would rename {filename} to {new_name}")
            else:
                os.rename(file_path, new_path)
                print(f"Renamed {filename} to {new_name}")
        except Exception as e:
            print(f"Error renaming {filename}: {e}")

# Test with dry run first
safe_rename_files('.', prefix='backup_', dry_run=True)

Practice: File Automation

Try It Yourself

Try simulating file automation:

Press Run to see output

What happened? You simulated organizing files by their extension. In a real automation script, you would use os.listdir() and shutil.move() to actually organize files.

Summary

In this lesson, you learned:

  • Automation: Using code to perform repetitive tasks
  • Benefits: Saves time, reduces errors, works continuously
  • File automation: Organizing and processing files
  • Data automation: Processing and cleaning data
  • Task automation: Automating workflows

Remember

If you find yourself doing the same task repeatedly, consider automating it! Start with simple scripts and build up to more complex automation.

End-of-Lesson Exercises

Think about these questions to reinforce what you've learned:

Exercise 1: Automation

What is automation and why is it useful? Give examples of repetitive tasks that could be automated.

Exercise 2: Automation Ideas

What repetitive tasks do you do that could be automated?