Automate everyday tasks with Python · Lesson 4 of 14

Rename, copy, move and organise files

Rename files with pathlib, copy and move them with shutil, avoid overwriting by accident, and sort a folder into sub-folders by type.

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

Now that you can find files, you can change them. Path.rename() gives a file a new name, shutil.copy() makes a copy and shutil.move() moves a file to another folder. shutil (shell utilities) is part of Python, so there is nothing to install.

Renaming files

rename() takes the new path and returns it. A common task is adding a date or a number to many names at once.

Pythoneditable
from pathlib import Path

scans = Path("scans")
for p in sorted(scans.iterdir(), key=lambda p: p.name):
    new = p.with_name("2026-03-15_" + p.name)
    p.rename(new)
    print(p.name, "->", new.name)

print(sorted(p.name for p in scans.iterdir()))
Output
scan1.pdf -> 2026-03-15_scan1.pdf
scan2.pdf -> 2026-03-15_scan2.pdf
scan3.pdf -> 2026-03-15_scan3.pdf
['2026-03-15_scan1.pdf', '2026-03-15_scan2.pdf', '2026-03-15_scan3.pdf']
Watch out: If the new name already exists, rename() behaves differently by system: Windows refuses with FileExistsError, while macOS and Linux silently replace the other file. Always check new.exists() before renaming, as shown below.

Copying files

shutil.copy(source, destination) copies a file. If the destination is a folder, the copy keeps its name. The original stays where it was, which makes copying a safe way to keep a backup.

Pythoneditable
import shutil
from pathlib import Path

backup = Path("backup")
backup.mkdir(exist_ok=True)

for p in sorted(Path("docs").glob("*.txt"), key=lambda p: p.name):
    shutil.copy(p, backup)

print("docs:  ", sorted(p.name for p in Path("docs").iterdir()))
print("backup:", sorted(p.name for p in backup.iterdir()))
Output
docs:   ['logo.png', 'plan.txt', 'todo.txt']
backup: ['plan.txt', 'todo.txt']

Organising a folder by file type

This is the classic automation job: look at each file's extension and move it into a sub-folder named after its type. Files without an extension go into other. shutil.move() with a folder as destination puts the file inside that folder. Notice that the file list is collected and sorted before anything moves: changing a folder while you are still listing it can give surprising results.

Pythoneditable
import shutil
from pathlib import Path

def show(folder):
    for p in sorted(folder.rglob("*"), key=lambda p: p.as_posix()):
        if p.is_file():
            print(" ", p.relative_to(folder).as_posix())

downloads = Path("downloads")
for p in sorted(downloads.iterdir(), key=lambda p: p.name):
    if not p.is_file():
        continue
    ext = p.suffix.lower()[1:] or "other"     # ".JPG" -> "jpg", "" -> "other"
    folder = downloads / ext
    folder.mkdir(exist_ok=True)
    shutil.move(p, folder)

show(downloads)
Output
  docx/letter.docx
  jpg/Holiday.JPG
  mp3/song.mp3
  other/README
  pdf/invoice_march.pdf
  png/scan.png
  xlsx/budget.xlsx

Never overwrite by accident

When two files end up with the same name, a careful script picks a free name instead: report.pdf, then report (1).pdf, report (2).pdf and so on, the way file managers do.

Pythoneditable
from pathlib import Path

def free_name(target):
    """Return target, or target with (1), (2)... added if it is taken."""
    n = 1
    candidate = target
    while candidate.exists():
        candidate = target.with_stem(f"{target.stem} ({n})")
        n += 1
    return candidate

inbox = Path("inbox")
for name in ["report.pdf", "summary.pdf"]:
    new = free_name(inbox / name)
    new.write_text("new file\n", encoding="utf-8")
    print("saved as", new.name)

print(sorted(p.name for p in inbox.iterdir()))
Output
saved as report (2).pdf
saved as summary.pdf
['report (1).pdf', 'report (2).pdf', 'report.pdf', 'summary.pdf']
Tip: Moving and renaming can be undone by hand, but deleting cannot. For your first real runs, have the script copy files instead of moving them, or keep the dry-run switch from lesson 1 (What automation is and how to plan a script).
On your Downloads folder (dry run)
from pathlib import Path

folder = Path.home() / "Downloads"
DRY_RUN = True

for p in sorted(folder.iterdir(), key=lambda p: p.name):
    if p.is_file():
        ext = p.suffix.lower()[1:] or "other"
        if DRY_RUN:
            print(f"would move {p.name} -> {ext}/")

Runs on your own computer, not on this page. Try it on a test copy of the folder first.

✎ Exercise

The photos folder mixes .jpeg and .jpg names. Rename every file whose extension is .jpeg (any case) so it ends in .jpg (skip it if that name is already taken), then print the sorted list of file names.

Hint: Compare p.suffix.lower() with ".jpeg" and rename to p.with_suffix(".jpg").

Your codewrite your answer, then Run
from pathlib import Path

photos = Path("photos")
# your code here

Expected output:

['cat.jpg', 'dog.jpg', 'sea.jpg']
Show a solution
Solutioneditable
from pathlib import Path

photos = Path("photos")
for p in sorted(photos.iterdir(), key=lambda p: p.name):
    if p.suffix.lower() == ".jpeg":
        new = p.with_suffix(".jpg")
        if not new.exists():
            p.rename(new)

print(sorted(p.name for p in photos.iterdir()))
Output
['cat.jpg', 'dog.jpg', 'sea.jpg']

Check yourself

1. What does shutil.copy("a.txt", "backup") do when backup is a folder?

2. What can happen on macOS or Linux if you rename() a file to a name that already exists?

3. Why collect and sort the files before moving them?

Spotted a mistake on this page? Tell us