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.
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.
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)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.
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()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.
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}")[dry run] would delete: old.log [dry run] would move to images: photo.jpg
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.
# 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.
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
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")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?
A dry run only reports the planned actions, so you can check them before anything changes.
2. Why split a script into small functions?
Small functions match the steps of your plan and can be tried one at a time.
3. What do the lines if __name__ == "__main__": and main() do at the end of a script file?
When you start the file itself, __name__ is "__main__", so main() runs. When another file imports it, it does not.