Python Basics: Automate Your Boring Tasks
Write your first scripts to rename files, sort data and save hours.
If you do the same computer task again and again, a short Python script can often do it for you. You do not need to be a programmer to start. Here are a few practical examples.
Set up
- Download Python from python.org and install it.
- Save your code in a file ending in
.py. - Run it from a terminal with
python your_script.py(on some systems the command ispython3).
Example 1: rename a batch of files
This renames every .jpg file in a folder to holiday_001.jpg, holiday_002.jpg and so on.
from pathlib import Path
folder = Path("photos")
for number, file in enumerate(sorted(folder.glob("*.jpg")), start=1):
file.rename(folder / f"holiday_{number:03d}.jpg")
Example 2: tidy your Downloads folder
This moves each file into a subfolder named after its file type.
from pathlib import Path
downloads = Path.home() / "Downloads"
for file in downloads.iterdir():
if file.is_file() and file.suffix:
target = downloads / file.suffix[1:].lower()
target.mkdir(exist_ok=True)
file.rename(target / file.name)
Example 3: sort a spreadsheet export
Assume a CSV file with a column called amount. This sorts the rows from largest to smallest.
import csv
with open("sales.csv", newline="") as f:
rows = list(csv.DictReader(f))
rows.sort(key=lambda row: float(row["amount"]), reverse=True)
for row in rows[:5]:
print(row)
Stay safe
- Run scripts that rename or move files on a copy of the folder first.
- Only run code you understand or trust.
- Read error messages from the bottom up. The last line usually says what went wrong.
Where next
Learn variables, loops, functions and reading files, and you can automate a surprising amount. If you prefer building something visual, try your first web page.