Tutorial

Automating Tasks with Python

Tutorial · Python

Cover: Automating Tasks with Python

Python's standard library plus a couple of popular packages cover most everyday automation without any heavyweight framework. A few small, real scripts show the pattern.

Bulk-renaming files

import os

folder = './photos'
for i, filename in enumerate(sorted(os.listdir(folder))):
    ext = os.path.splitext(filename)[1]
    new_name = f'photo_{i+1:03d}{ext}'
    os.rename(os.path.join(folder, filename), os.path.join(folder, new_name))

splitext separates a filename from its extension so the rename preserves .jpg, .png, and so on rather than clobbering it. The :03d format pads numbers with zeros so files sort correctly (001, 002, ... 010, not 1, 10, 2).

Scraping a simple webpage

import requests
from bs4 import BeautifulSoup

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

titles = [h2.text.strip() for h2 in soup.find_all('h2', class_='article-title')]
print(titles)

requests fetches the raw HTML; BeautifulSoup parses it into a tree you can search by tag and class. This pattern covers a large share of "pull data off a static page" tasks.

Check robots.txt and terms of service first. Not every site allows scraping, and some actively block it. Respect rate limits, identify your scraper with a real User-Agent, and never scrape data you don't have the right to use.

Reading and writing CSVs without extra dependencies

import csv

with open('data.csv', newline='') as f:
    reader = csv.DictReader(f)
    rows = [row for row in reader if float(row['amount']) > 100]

with open('filtered.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())
    writer.writeheader()
    writer.writerows(rows)

DictReader/DictWriter let you work with rows as dictionaries keyed by column header, instead of tracking column positions by index.

Scheduling it to run itself

On Linux or macOS, a cron entry (crontab -e) runs a script on a schedule with no code changes needed:

0 8 * * * /usr/bin/python3 /home/user/scripts/daily_report.py

On Windows, Task Scheduler does the equivalent job through a GUI. Either way, the script itself doesn't need to know it's being scheduled — it just runs top to bottom, the same as if you'd typed the command yourself.

Comments