Automation

How to Write Your First Python Automation Script

Start automation with a repeatable, reversible task. Transform data in memory, inspect the output, and only add file writes after you understand the result.

Step by step

  1. Write down the input and desired output.
  2. Keep the first version read-only.
  3. Normalize and validate each item.
  4. Add logging and a dry-run option before automating file changes.

Run this example

Use Python 3. Copy the code into a file or interactive Python environment.

raw = ["  invoice A  ", "Invoice B", "  invoice C"]
cleaned = [item.strip().title() for item in raw]
for before, after in zip(raw, cleaned):
    print(f"{before!r} -> {after!r}")

Expected output

'  invoice A  ' -> 'Invoice A'
'Invoice B' -> 'Invoice B'
'  invoice C' -> 'Invoice C'

Common issue

Avoid automating deletion or renaming until you have backups and a dry-run preview.

Try it yourself

Modify the list to contain five messy labels and preview the cleaned values.

Define the input and preview the result

A useful first automation has a narrow contract: take a list of names, normalize surrounding spaces, and show suggested filenames. Separating planning from writing lets you inspect the result before changing files. Start with sample data and keep original inputs available.

Plan filenames without renaming files

Path handles suffixes; casefold makes comparison consistent. The script prints plans only. It does not touch your filesystem.

from pathlib import Path
names = [" Report.PDF ", "notes.TXT"]
for name in names:
    source = Path(name.strip())
    target = source.stem.casefold().replace(" ", "-") + source.suffix.casefold()
    print(f"{name.strip()} -> {target}")

Expected output

Report.PDF -> report.pdf
notes.TXT -> notes.txt

Move from preview to a dependable workflow

Before adding a rename operation, check that sources exist and that two names cannot map to the same destination. Reject collisions instead of overwriting a file. Record each planned operation and test on a disposable folder. A preview should show the same paths that the later operation will use.

Exercise

Add " Sales Notes.CSV ". Its planned output should be sales-notes.csv. Then add both "A.txt" and "a.txt"; explain why the lowercased destinations collide. Implement duplicate detection before any file operations.

Troubleshooting

A relative path is resolved from the working directory, which may differ from the script's folder. A permission error means the operation was denied; repeatedly retrying cannot fix an incorrect target or missing access.

Keep learning

Read the relevant documentation · Free foundational resources

Related guides: Python For Loops vs While Loops: When to Use Each and 10 Useful Python Scripts for Beginners.

Interested in applying these skills to a product? Explore the optional Python to Profit course. It focuses on product and business building, not replacing foundational Python study.