Automating Boring Tasks with Python
A practical starter for scripting the tedious stuff — files, APIs and small tools — with the error handling that makes a script trustworthy.
Python's sweet spot is the quick script that saves you an hour of clicking. Here's a practical starting point.
Working with files
The modern way uses pathlib:
from pathlib import Path
for f in Path("downloads").glob("*.pdf"):
print(f.name, f.stat().st_size)A tiny "sort files into folders by extension" tool:
from pathlib import Path
src = Path("downloads")
for f in src.iterdir():
if f.is_file():
dest = src / f.suffix.lstrip(".").lower() or "misc"
dest.mkdir(exist_ok=True)
f.rename(dest / f.name)Calling an API
The requests library makes HTTP trivial:
import requests
r = requests.get("https://api.github.com/repos/python/cpython", timeout=10)
r.raise_for_status() # turn a 4xx/5xx into an exception
data = r.json()
print(data["stargazers_count"])raise_for_status() is the line beginners forget — without it, a failed request silently returns an error page and your code marches on with garbage.
Make it trustworthy: handle errors and input
A script you'll rely on should fail clearly, not silently:
import sys
from pathlib import Path
def main(argv):
if len(argv) != 2:
sys.exit("usage: tidy.py <folder>")
folder = Path(argv[1])
if not folder.is_dir():
sys.exit(f"not a directory: {folder}")
# ... do the work ...
if __name__ == "__main__":
main(sys.argv)Two habits that pay off:
- Validate inputs and exit with a helpful message, not a traceback.
- Guard with
if __name__ == "__main__":so the file can be imported without running.
Scheduling it
Once a script works, let the OS run it:
# cron: every day at 03:00
0 3 * * * /usr/bin/python3 /home/you/tidy.py /home/you/downloads(On Windows, Task Scheduler does the same job.)
Takeaways
pathlibfor files,requestsfor HTTP — and alwaysraise_for_status().- Validate inputs and exit with a clear message; guard with
if __name__ == "__main__":. - Hand working scripts to cron or Task Scheduler to run unattended.
- Keep dependencies in a venv so projects don't collide.