DEV Community

lufumeiying
lufumeiying

Posted on

Python Automation Scripts: A Beginner's Guide to Automating Daily Tasks

Python Automation Scripts: A Beginner's Guide to Automating Daily Tasks

Have you ever spent hours doing the same repetitive task over and over?

Checking emails, organizing files, sending reports, tracking data... What if I told you Python can do all of this for you automatically?

The best part? You don't need to be a programmer to get started.


🎯 What You'll Learn

graph LR
    A[Start Here] --> B[Python Basics]
    B --> C[Simple Scripts]
    C --> C1[File Automation]
    C --> C2[Email Automation]
    C --> C3[Web Scraping]
    C1 --> D[Real Projects]
    C2 --> D
    C3 --> D
    D --> E[Save Hours Daily!]

    style A fill:#4caf50
    style E fill:#2196f3
Enter fullscreen mode Exit fullscreen mode

By the end of this guide, you'll know how to:

  • ✅ Automate file organization
  • ✅ Send automatic emails
  • ✅ Track website changes
  • ✅ Generate reports automatically
  • ✅ Save 2+ hours every day

🐍 Why Python for Automation?

The Perfect Choice

Python is ideal for automation because:

mindmap
  root((Python))
    Easy to Learn
      Simple syntax
      Readable code
      Huge community
    Powerful Libraries
      os - File operations
      smtplib - Emails
      requests - Web access
      pandas - Data
    Cross-Platform
      Windows
      Mac
      Linux
    Free
      Open source
      No cost
      Active development
Enter fullscreen mode Exit fullscreen mode

📊 Python vs Other Tools

Feature Python Excel Macros Shell Scripts AutoHotkey
Learning Curve Easy Medium Hard Medium
Cross-Platform ✅ Yes ❌ Windows ❌ Unix ❌ Windows
Power ⭐⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐
Free ✅ Yes ❌ No ✅ Yes ✅ Yes
Data Handling ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐ ⭐⭐

Winner: Python (free + powerful + easy)


🚀 Quick Start Guide

Step 1: Install Python

Windows/Mac/Linux: Download from python.org

Verify installation:

python --version
# Output: Python 3.11.x
Enter fullscreen mode Exit fullscreen mode

Step 2: Your First Automation Script

Create hello_automation.py:

#!/usr/bin/env python3
"""
My First Automation Script
This script greets you and shows the current time
"""

from datetime import datetime

def greet():
    """Greet the user"""
    now = datetime.now()
    hour = now.hour

    if 5 <= hour < 12:
        greeting = "Good morning!"
    elif 12 <= hour < 17:
        greeting = "Good afternoon!"
    elif 17 <= hour < 21:
        greeting = "Good evening!"
    else:
        greeting = "Good night!"

    print(f"{greeting}")
    print(f"Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
    print("Welcome to Python automation!")

if __name__ == "__main__":
    greet()
Enter fullscreen mode Exit fullscreen mode

Run it:

python hello_automation.py
Enter fullscreen mode Exit fullscreen mode

Output:

Good afternoon!
Current time: 2026-04-02 16:30:00
Welcome to Python automation!
Enter fullscreen mode Exit fullscreen mode

📁 Project 1: File Organizer

The Problem

Downloads folder is a mess?

Downloads/
├── report.pdf
├── vacation.jpg
├── data.xlsx
├── script.py
├── music.mp3
└── ... (hundreds of files)
Enter fullscreen mode Exit fullscreen mode

The Solution

Create file_organizer.py:

#!/usr/bin/env python3
"""
File Organizer
Automatically organizes files into folders by type
"""

import os
import shutil
from pathlib import Path

# File categories
CATEGORIES = {
    'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
    'Documents': ['.pdf', '.doc', '.docx', '.txt', '.xls', '.xlsx'],
    'Code': ['.py', '.js', '.html', '.css', '.java'],
    'Music': ['.mp3', '.wav', '.flac', '.aac'],
    'Videos': ['.mp4', '.avi', '.mov', '.mkv'],
    'Archives': ['.zip', '.rar', '.7z', '.tar']
}

def organize_folder(folder_path):
    """
    Organize files in the specified folder

    Args:
        folder_path: Path to the folder to organize
    """
    folder = Path(folder_path)

    if not folder.exists():
        print(f"Error: {folder_path} does not exist")
        return

    # Create category folders
    for category in CATEGORIES:
        category_path = folder / category
        category_path.mkdir(exist_ok=True)

    # Move files to appropriate folders
    moved_count = 0

    for file in folder.iterdir():
        if file.is_file():
            # Get file extension
            extension = file.suffix.lower()

            # Find the right category
            for category, extensions in CATEGORIES.items():
                if extension in extensions:
                    # Move the file
                    destination = folder / category / file.name

                    # Handle duplicate names
                    if destination.exists():
                        destination = folder / category / f"{file.stem}_{moved_count}{file.suffix}"

                    shutil.move(str(file), str(destination))
                    print(f"Moved: {file.name}{category}/")
                    moved_count += 1
                    break

    print(f"\n✅ Organized {moved_count} files!")

if __name__ == "__main__":
    # Organize Downloads folder
    downloads = Path.home() / "Downloads"
    organize_folder(downloads)
Enter fullscreen mode Exit fullscreen mode

Run it:

python file_organizer.py
Enter fullscreen mode Exit fullscreen mode

Result:

Downloads/
├── Images/
│   └── vacation.jpg
├── Documents/
│   ├── report.pdf
│   └── data.xlsx
├── Code/
│   └── script.py
└── Music/
    └── music.mp3
Enter fullscreen mode Exit fullscreen mode

📧 Project 2: Email Automation

The Problem

Sending the same email to multiple recipients?

The Solution

Create email_automation.py:

#!/usr/bin/env python3
"""
Email Automation
Send personalized emails to multiple recipients
"""

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

class EmailAutomation:
    """Automated email sender"""

    def __init__(self, smtp_server, port, email, password):
        """
        Initialize email automation

        Args:
            smtp_server: SMTP server address
            port: SMTP port
            email: Your email address
            password: Your email password
        """
        self.smtp_server = smtp_server
        self.port = port
        self.email = email
        self.password = password

    def send_email(self, to_email, subject, body):
        """
        Send an email

        Args:
            to_email: Recipient email
            subject: Email subject
            body: Email body
        """
        # Create message
        message = MIMEMultipart()
        message['From'] = self.email
        message['To'] = to_email
        message['Subject'] = subject

        # Add body
        message.attach(MIMEText(body, 'plain'))

        # Send
        try:
            server = smtplib.SMTP(self.smtp_server, self.port)
            server.starttls()
            server.login(self.email, self.password)
            server.send_message(message)
            server.quit()
            print(f"✅ Email sent to {to_email}")
            return True
        except Exception as e:
            print(f"❌ Failed to send to {to_email}: {e}")
            return False

    def send_bulk(self, recipients, subject_template, body_template):
        """
        Send personalized emails to multiple recipients

        Args:
            recipients: List of (name, email) tuples
            subject_template: Subject template
            body_template: Body template
        """
        success_count = 0

        for name, email in recipients:
            # Personalize
            subject = subject_template.format(name=name)
            body = body_template.format(name=name, date=datetime.now().strftime('%Y-%m-%d'))

            if self.send_email(email, subject, body):
                success_count += 1

        print(f"\n📊 Sent {success_count}/{len(recipients)} emails")

if __name__ == "__main__":
    # Example usage
    # Note: Use environment variables for credentials!

    # Recipients
    recipients = [
        ("Alice", "alice@example.com"),
        ("Bob", "bob@example.com"),
        ("Charlie", "charlie@example.com")
    ]

    # Templates
    subject_template = "Weekly Update for {name}"
    body_template = """
Hi {name},

I hope this email finds you well.

Here's your weekly update for {date}:

• Progress: On track
• Next steps: Continue automation
• Questions? Just reply to this email

Best regards,
Automation Bot
"""

    # Note: Replace with your actual credentials
    # email_automation = EmailAutomation(
    #     smtp_server="smtp.gmail.com",
    #     port=587,
    #     email="your_email@gmail.com",
    #     password="your_app_password"
    # )
    # email_automation.send_bulk(recipients, subject_template, body_template)

    print("📧 Email automation script ready!")
    print("⚠️  Configure your email credentials to use")
Enter fullscreen mode Exit fullscreen mode

🌐 Project 3: Website Monitoring

The Problem

Need to know when a website changes?

The Solution

Create website_monitor.py:

#!/usr/bin/env python3
"""
Website Monitor
Track changes to websites and get notifications
"""

import requests
import hashlib
import json
from datetime import datetime
from pathlib import Path

class WebsiteMonitor:
    """Monitor website changes"""

    def __init__(self, cache_file="website_cache.json"):
        """
        Initialize website monitor

        Args:
            cache_file: File to store website hashes
        """
        self.cache_file = Path(cache_file)
        self.cache = self.load_cache()

    def load_cache(self):
        """Load cached website data"""
        if self.cache_file.exists():
            with open(self.cache_file, 'r') as f:
                return json.load(f)
        return {}

    def save_cache(self):
        """Save cache to file"""
        with open(self.cache_file, 'w') as f:
            json.dump(self.cache, f, indent=2)

    def get_hash(self, content):
        """Get MD5 hash of content"""
        return hashlib.md5(content.encode()).hexdigest()

    def check_website(self, url):
        """
        Check if website has changed

        Args:
            url: Website URL

        Returns:
            True if changed, False otherwise
        """
        try:
            response = requests.get(url, timeout=10)
            content = response.text
            current_hash = self.get_hash(content)

            if url in self.cache:
                if self.cache[url] != current_hash:
                    print(f"🔄 {url} has CHANGED!")
                    self.cache[url] = current_hash
                    self.save_cache()
                    return True
                else:
                    print(f"{url} unchanged")
                    return False
            else:
                print(f"📝 {url} added to monitoring")
                self.cache[url] = current_hash
                self.save_cache()
                return False

        except Exception as e:
            print(f"❌ Error checking {url}: {e}")
            return False

    def monitor_multiple(self, urls):
        """
        Monitor multiple websites

        Args:
            urls: List of website URLs
        """
        print(f"=== Website Monitor ===")
        print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")

        changes_detected = 0

        for url in urls:
            if self.check_website(url):
                changes_detected += 1

        print(f"\n📊 {changes_detected} change(s) detected")
        return changes_detected

if __name__ == "__main__":
    # Websites to monitor
    websites = [
        "https://news.ycombinator.com",
        "https://www.reddit.com/r/programming",
        "https://github.com/trending"
    ]

    monitor = WebsiteMonitor()
    monitor.monitor_multiple(websites)
Enter fullscreen mode Exit fullscreen mode

📊 Project 4: Report Generator

The Problem

Creating the same report every day?

The Solution

Create report_generator.py:

#!/usr/bin/env python3
"""
Report Generator
Generate automated reports from data
"""

import json
from datetime import datetime, timedelta
from pathlib import Path

class ReportGenerator:
    """Automated report generator"""

    def __init__(self, output_dir="reports"):
        """
        Initialize report generator

        Args:
            output_dir: Directory to save reports
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)

    def generate_daily_report(self, data):
        """
        Generate daily report

        Args:
            data: Dictionary containing report data

        Returns:
            Path to generated report
        """
        today = datetime.now()
        report_date = today.strftime('%Y-%m-%d')

        # Generate report content
        report = f"""
# Daily Report - {report_date}

Generated: {today.strftime('%Y-%m-%d %H:%M:%S')}

---

## Summary

**Total Items**: {data.get('total_items', 0)}
**Completed**: {data.get('completed', 0)}
**In Progress**: {data.get('in_progress', 0)}
**Pending**: {data.get('pending', 0)}

---

## Details

"""

        # Add details
        if 'details' in data:
            for detail in data['details']:
                report += f"- {detail}\n"

        report += f"""
---

## Metrics

- Completion Rate: {(data.get('completed', 0) / max(data.get('total_items', 1), 1)) * 100:.1f}%
- Average Time: {data.get('avg_time', 'N/A')}

---

## Next Steps

1. Review pending items
2. Continue in-progress work
3. Plan for tomorrow

---

*Report generated automatically*
"""

        # Save report
        filename = f"daily_report_{report_date}.md"
        filepath = self.output_dir / filename

        with open(filepath, 'w') as f:
            f.write(report)

        print(f"✅ Report generated: {filepath}")
        return filepath

    def generate_weekly_summary(self, daily_reports):
        """
        Generate weekly summary from daily reports

        Args:
            daily_reports: List of daily report data

        Returns:
            Path to generated summary
        """
        week_start = datetime.now() - timedelta(days=7)
        week_end = datetime.now()

        # Calculate totals
        total_items = sum(r.get('total_items', 0) for r in daily_reports)
        total_completed = sum(r.get('completed', 0) for r in daily_reports)

        # Generate summary
        summary = f"""
# Weekly Summary

Period: {week_start.strftime('%Y-%m-%d')} to {week_end.strftime('%Y-%m-%d')}

---

## Overview

**Total Items This Week**: {total_items}
**Total Completed**: {total_completed}
**Completion Rate**: {(total_completed / max(total_items, 1)) * 100:.1f}%

---

## Daily Breakdown

"""

        for i, report in enumerate(daily_reports, 1):
            summary += f"Day {i}: {report.get('completed', 0)} completed\n"

        summary += """
---

## Highlights

- Best day: [Identify from data]
- Areas for improvement: [Analysis]

---

*Weekly summary generated automatically*
"""

        # Save summary
        filename = f"weekly_summary_{week_end.strftime('%Y-%m-%d')}.md"
        filepath = self.output_dir / filename

        with open(filepath, 'w') as f:
            f.write(summary)

        print(f"✅ Weekly summary generated: {filepath}")
        return filepath

if __name__ == "__main__":
    # Example usage
    generator = ReportGenerator()

    # Daily data
    daily_data = {
        'total_items': 10,
        'completed': 7,
        'in_progress': 2,
        'pending': 1,
        'details': [
            'Completed Python automation script',
            'Generated daily report',
            'Updated documentation'
        ],
        'avg_time': '2.5 hours'
    }

    generator.generate_daily_report(daily_data)
Enter fullscreen mode Exit fullscreen mode

📈 Automation Impact

Time Saved

graph TD
    A[Daily Tasks] --> B[Manual: 3 hours]
    A --> C[Automated: 30 minutes]

    B --> D[Weekly: 15 hours]
    C --> E[Weekly: 2.5 hours]

    D --> F[Yearly: 780 hours]
    E --> G[Yearly: 130 hours]

    F --> H[❌ Time Lost]
    G --> I[✅ Time Saved: 650 hours/year!]

    style H fill:#f44336
    style I fill:#4caf50
Enter fullscreen mode Exit fullscreen mode

💡 Best Practices

1. Start Small

Don't automate everything at once.

Week 1: Automate one task
Week 2: Add another automation
Week 3: Combine into workflow
Week 4: Optimize and refine
Enter fullscreen mode Exit fullscreen mode

2. Use Virtual Environments

# Create virtual environment
python -m venv automation_env

# Activate it
source automation_env/bin/activate  # Mac/Linux
# OR
automation_env\Scripts\activate  # Windows

# Install packages
pip install requests pandas
Enter fullscreen mode Exit fullscreen mode

3. Schedule Your Scripts

Using crontab (Mac/Linux):

# Edit crontab
crontab -e

# Add scheduled tasks
0 9 * * * python /path/to/daily_report.py
0 18 * * * python /path/to/file_organizer.py
Enter fullscreen mode Exit fullscreen mode

4. Handle Errors Gracefully

try:
    result = automate_task()
except Exception as e:
    print(f"Error: {e}")
    send_error_notification(e)
    # Fallback plan
Enter fullscreen mode Exit fullscreen mode

🎓 Learning Path

Week 1: Basics

  • Day 1-2: Python installation and setup
  • Day 3-4: Basic scripts
  • Day 5-7: File operations

Week 2: Web and Email

  • Day 1-3: Web requests and APIs
  • Day 4-5: Email automation
  • Day 6-7: Combining skills

Week 3: Data and Reports

  • Day 1-3: Data processing
  • Day 4-5: Report generation
  • Day 6-7: Complete automation

🎬 Take Action

Your First Week

  1. Day 1: Install Python
  2. Day 2: Run your first script
  3. Day 3: Organize your Downloads folder
  4. Day 4: Send automated emails
  5. Day 5: Monitor a website
  6. Day 6: Generate a report
  7. Day 7: Combine everything!

📝 Summary

mindmap
  root((Python Automation))
    Projects
      File Organizer
      Email Automation
      Website Monitor
      Report Generator
    Benefits
      Save 2+ hours daily
      Reduce errors
      Focus on important work
    Getting Started
      Install Python
      Write first script
      Schedule tasks
      Iterate and improve
Enter fullscreen mode Exit fullscreen mode

💬 Final Thoughts

Automation isn't about being lazy - it's about being smart.

Every hour you spend automating saves 10+ hours in the future.

The best time to start was yesterday. The second best time is now.


What will you automate first? Share your ideas in the comments! 👇


Last updated: April 2026
All scripts tested and verified
No affiliate links or sponsored content

Top comments (0)