Automate everyday tasks with Python · Lesson 1 of 14

What automation is and how to plan a script

Learn which everyday jobs a Python script can do for you and how to plan one: input, steps, output and a safe dry run first.

About 10 minutes · code runs in your browser, nothing to install

Automation means letting a program do a job you would otherwise do by hand, again and again: renaming a hundred photos, sorting a messy Downloads folder, copying numbers from one file into a report, or cleaning a list of names. A script that takes ten minutes to write can save you that ten minutes every week.

  • Files and folders: rename, copy, move and sort files by type or date.
  • Data files: read CSV and JSON files, combine them, write new ones.
  • Text: clean names, find e-mail addresses or dates, fill in templates.
  • Reports: count, total and summarise, then write the result to a file.

Input, steps, output

Almost every automation script has the same shape. It reads some input (a folder, a file, a list), works through it step by step, and produces output (moved files, a new file, a printed summary). Here the input is a list of file names; the script picks out the PDF files.

Pythoneditable
names = ["report.pdf", "photo.jpg", "notes.txt", "invoice.pdf"]

pdfs = [name for name in names if name.endswith(".pdf")]

print("Found", len(pdfs), "PDF files:")
for name in sorted(pdfs):
    print("-", name)
Output
Found 2 PDF files:
- invoice.pdf
- report.pdf

Plan before you code

Before writing code, write the steps in plain words, one per line. Each step usually becomes one small function. Small functions are easy to test on their own, and main() reads like the plan.

Pythoneditable
def find_files(names, extension):
    """Step 1: keep the names that end with the extension (any case)."""
    return sorted(n for n in names if n.lower().endswith(extension))

def make_report(found):
    """Step 2: turn the result into lines of text."""
    lines = [f"{len(found)} file(s) found"]
    lines += [f"  {name}" for name in found]
    return "\n".join(lines)

def main():
    names = ["Budget.XLSX", "trip.jpg", "budget-old.xlsx", "cv.docx"]
    found = find_files(names, ".xlsx")
    print(make_report(found))   # Step 3: show the result

main()
Output
2 file(s) found
  Budget.XLSX
  budget-old.xlsx

A dry run first

Scripts that move or delete files can do a lot of damage in a second. A good habit is a dry run: a switch that makes the script only print what it would do. When the printed plan looks right, you turn the switch off.

Pythoneditable
DRY_RUN = True

actions = [("old.log", "delete"), ("photo.jpg", "move to images"), ("notes.txt", "keep")]

for name, action in actions:
    if action == "keep":
        continue
    if DRY_RUN:
        print(f"[dry run] would {action}: {name}")
    else:
        print(f"{action}: {name}")
Output
[dry run] would delete: old.log
[dry run] would move to images: photo.jpg
Tip: Test new scripts on a copy of your files, in a test folder, never on the only copy of something important.

Where the code runs

The examples in this course run in your browser, inside a small private folder that starts empty (or with the example files we give it). That is perfect for practising: nothing on your computer is touched. When a step needs your real computer, such as your own Downloads folder or the terminal, we show the code in a grey box that does not run on the page, and explain how to use it.

tidy.py
# Save this as tidy.py and run it in a terminal with:  python tidy.py
def main():
    print("Hello from my first automation script")

if __name__ == "__main__":
    main()

The usual layout of a script file. The last two lines run main() only when you start the file directly.

✎ Exercise

Write a dry run for a clean-up script. For every name in files that ends with .tmp, print would delete: <name>. At the end print the count as <n> files would be deleted.

Hint: Loop over the list, test each name with endswith(".tmp") and keep a counter.

Your codewrite your answer, then Run
files = ["a.tmp", "notes.txt", "b.tmp", "draft.docx", "cache.tmp"]
# your code here

Expected output:

would delete: a.tmp
would delete: b.tmp
would delete: cache.tmp
3 files would be deleted
Show a solution
Solutioneditable
files = ["a.tmp", "notes.txt", "b.tmp", "draft.docx", "cache.tmp"]
count = 0
for name in files:
    if name.endswith(".tmp"):
        print("would delete:", name)
        count += 1
print(count, "files would be deleted")
Output
would delete: a.tmp
would delete: b.tmp
would delete: cache.tmp
3 files would be deleted

Check yourself

1. What is a dry run?

2. Why split a script into small functions?

3. What do the lines if __name__ == "__main__": and main() do at the end of a script file?

Spotted a mistake on this page? Tell us