Organising files safely.
Discover, copy, move, and remove files without turning a small script into data loss.
Start here.
A directory groups file paths. A Path object has meaningful parts: parent is its containing directory, name is the last filename, stem is the name without its final suffix, and suffix is the extension-like ending. The expression Path('archive') / source.name joins path pieces; the slash operator here is path joining, not numeric division. This avoids guessing where separators belong on different operating systems.
glob('*.txt') asks for paths directly inside a directory whose names end in .txt. The star means any sequence of filename characters in this pattern. rglob searches through nested directories as well, so it can select much more than a reader expects. The chapter's first example only prints source and destination pairs. That output is a plan: it reveals what the rule would affect without copying or moving a file.
Copying creates another file; moving changes its location; deleting removes one. These operations can overwrite or lose data if two sources map to the same destination. A reliable script separates discovery from action, checks whether destinations already exist, and gives a clear rule for collisions. shutil.copy2 copies file content and tries to preserve metadata; Path.rename renames or moves within its filesystem. The safety principle is to understand the full path set before changing it.
Build the model.
File automation is powerful because one rule can affect hundreds of paths. Start by discovering candidates with pathlib glob or rglob, then print the proposed changes before performing them. A path has parts such as parent, name, suffix, and stem; use those properties rather than slicing strings to invent a new filename.
Use shutil.copy2 when you need a copy with metadata where possible, Path.rename for a move on the same filesystem, and shutil.move when crossing filesystems may be involved. Deletion should be the last operation you add, after you can show exactly which files are selected. A dry run is a normal feature of a trustworthy automation script.
How it works.
Separate planning from execution. One function can produce pairs of source and destination paths; another can apply only a reviewed plan. Check for destination collisions before moving anything. If two source files map to the same destination name, a naive loop may overwrite the first result. A stable naming rule and explicit collision policy prevent that surprise.
Replacing a file safely can require writing a temporary file in the same directory and then using an atomic rename where the filesystem supports it. This reduces the chance of leaving a half-written final file. Backups still matter because an atomic replacement can atomically install the wrong content. Test on a disposable directory before touching important files.
Read it line by line.
from pathlib import Path
for source in Path('inbox').glob('*.txt'):
destination = Path('archive') / source.name
print(f'{source} -> {destination}')glob selects text files directly inside inbox. Each source path contributes only its name to a new path under archive. The script prints a plan and changes no files. The displayed pairs reveal the source, destination, and any collisions that a later copy or move operation would need to handle.
See the rule again.
from pathlib import Path
from shutil import copy2
source_dir = Path('inbox')
destination_dir = Path('archive')
destination_dir.mkdir(exist_ok=True)
for source in source_dir.glob('*.txt'):
destination = destination_dir / source.name
if not destination.exists():
copy2(source, destination)The directory is created if needed. Each candidate is copied only when the destination name is unused. This is a simple collision policy; production code should report skipped files and consider races if another process can write there at the same time.
A mistake to avoid.
rglob searches recursively, so a broad pattern may include generated output or backups. Exclude the destination directory from discovery or you can repeatedly process your own results.