Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - Why Automate with Python?
  • - Automating File Operations
  • - Web Scraping for Automation
  • - Automating Emails
  • - Scheduling Tasks
  • - Best Practices for Automation Scripts
  • - Mini Exercise

28. Python for Automation Scripts

Level: AdvancedDuration: 32m

Why Automate with Python?

Python is perfect for automation because it’s simple, readable, and has a rich ecosystem of libraries. Automation saves time, reduces human error, and allows you to focus on more meaningful work.

Automating File Operations

Python can create, read, modify, and organize files automatically using the built-in `os` and `shutil` modules.

python
import os
import shutil

# Create a folder
os.makedirs('backup', exist_ok=True)

# Move all .txt files to the backup folder
for file in os.listdir('.'):
    if file.endswith('.txt'):
        shutil.move(file, 'backup/' + file)

Web Scraping for Automation

Python libraries like `requests` and `BeautifulSoup` allow you to scrape websites for data, which can then be processed or stored automatically.

python
import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Print all headings
for h in soup.find_all('h2'):
    print(h.text)

Automating Emails

You can send automated emails using `smtplib` in Python. This is useful for notifications, reports, or reminders.

python
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg.set_content('Hello! This is an automated message.')
msg['Subject'] = 'Automation Test'
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient@example.com'

with smtplib.SMTP('smtp.example.com', 587) as server:
    server.starttls()
    server.login('your_email@example.com', 'password')
    server.send_message(msg)

Scheduling Tasks

Python scripts can be scheduled to run automatically using OS-level schedulers like Cron (Linux/macOS) or Task Scheduler (Windows).

bash
# Example cron job to run a Python script every day at 7am
0 7 * * * /usr/bin/python3 /path/to/script.py

Best Practices for Automation Scripts

  • Handle exceptions to prevent script crashes.
  • Log actions and errors using the `logging` module.
  • Keep scripts modular with functions.
  • Avoid hardcoding sensitive information; use environment variables or config files.
  • Test scripts thoroughly before scheduling them.

Mini Exercise

Create a Python script that automatically backs up all `.csv` files in a folder to a `backup` folder and logs the actions in a `log.txt` file. Bonus: schedule it to run daily.

Learn More About Python Automation