Python Intermediate - Lesson 04 - Intermediate 04 - Organizing Files Safely
Python Intermediate · Lesson 04
Organizing Files Safely
Python can inspect folders and help sort files into a cleaner structure.
In this lesson, you’ll use pathlib to find files and
shutil to copy them into extension-based folders.
1. Inspect a folder
Path.iterdir() lists the immediate children of a directory.
It does not search inside subfolders. Check that the path is a directory
before inspecting it.
from pathlib import Path
folder = Path("organizer_demo/inbox")
if folder.is_dir():
for path in folder.iterdir():
print(path.name)
Use path.is_file() to distinguish files from folders.
path.suffix returns a file extension such as
".txt".
2. Select files and build destination paths
Use glob() to select direct children matching a pattern. The
destination can be built from the extension and original filename.
from pathlib import Path
source_folder = Path("organizer_demo/inbox")
text_files = source_folder.glob("*.txt")
destination_folder = Path("organizer_demo/organized") / "txt"
for source_path in text_files:
destination_path = destination_folder / source_path.name
print(f"{source_path} -> {destination_path}")
This prints a plan only. It does not create a folder or copy anything. Previewing a plan is a good habit before a script changes files.
3. Copy files without replacing existing ones
shutil.copy2() copies a file and keeps its basic metadata.
Create the destination folder first, then check whether a same-named file
already exists.
import shutil
from pathlib import Path
source_path = Path("organizer_demo/inbox/notes.txt")
destination_folder = Path("organizer_demo/organized/txt")
destination_folder.mkdir(parents=True, exist_ok=True)
destination_path = destination_folder / source_path.name
if not destination_path.exists():
shutil.copy2(source_path, destination_path)
print("File copied.")
else:
print("Skipped: a file with that name already exists.")
4. Copy or move?
copy2() leaves the original in place. shutil.move()
relocates it, so it no longer remains in its original folder. Start with
a copy or a dry run while you are learning; only move files when you
intend to change their location.
Hands-on exercises
-
Use
Path.glob()to list only the.txtfiles directly inside a folder namedinbox. - Build a destination folder named after a file’s extension. Create it if needed, then copy the file only if the destination does not already exist.
Show Solution & Common Mistakes
Exercise 1 — one possible solution
from pathlib import Path
inbox = Path("inbox")
for path in inbox.glob("*.txt"):
if path.is_file():
print(path.name)
Exercise 2 — one possible solution
import shutil
from pathlib import Path
source_path = Path("inbox/notes.txt")
extension = source_path.suffix.lower().lstrip(".") or "no_extension"
destination_folder = Path("organized") / extension
destination_folder.mkdir(parents=True, exist_ok=True)
destination_path = destination_folder / source_path.name
if source_path.is_file() and not destination_path.exists():
shutil.copy2(source_path, destination_path)
print("Copied.")
else:
print("Skipped: source is missing or destination already exists.")
Common mistakes:
- Scanning a folder you did not intend to change. Use a specific test folder and print the source and destination paths first.
-
Assuming
iterdir()searches recursively. It only lists direct children. - Copying over an existing destination file without checking first.
-
Forgetting that an extension may be uppercase or missing. Normalize it
with
.lower()and decide how to handle an empty suffix.
Quick quiz
Choose an answer, then select Check answer.
1. What does Path.iterdir() list?
2. Which operation keeps the original file?
3. Why check destination_path.exists() before copying?
Mini-project: Safe File Organizer
Build a small organizer that copies files from a dedicated inbox into folders named by extension. It previews every planned copy and requires an explicit confirmation before copying.
Requirements:
- Work only inside
organizer_demo/inbox. - Create a few sample text files only when they do not already exist.
- Group files into subfolders such as
txt,csv, ormd. - Print the copy plan before changing anything.
- Copy only after the user types
COPY. - Skip destination files that already exist; never delete or move originals.
Hints: Use Path.iterdir() and
path.is_file() to find files. Build an extension folder from
path.suffix. Keep the source folder separate from the
destination folder.
Show Full Project Solution
import shutil
from pathlib import Path
base_folder = Path("organizer_demo")
inbox = base_folder / "inbox"
organized = base_folder / "organized"
inbox.mkdir(parents=True, exist_ok=True)
sample_files = {
"ideas.txt": "A place for project ideas.",
"reading.csv": "title,pages\nPython Notes,12\n",
"plan.md": "# Practice plan\n"
}
for filename, content in sample_files.items():
sample_path = inbox / filename
if not sample_path.exists():
sample_path.write_text(content, encoding="utf-8")
copy_plan = []
for source_path in inbox.iterdir():
if not source_path.is_file():
continue
extension = source_path.suffix.lower().lstrip(".") or "no_extension"
destination_path = organized / extension / source_path.name
copy_plan.append((source_path, destination_path))
if not copy_plan:
print("The inbox has no files to organize.")
else:
print("Preview of planned copies:")
for source_path, destination_path in copy_plan:
print(f"{source_path} -> {destination_path}")
confirmation = input('Type COPY to make these copies: ').strip()
if confirmation == "COPY":
for source_path, destination_path in copy_plan:
destination_path.parent.mkdir(parents=True, exist_ok=True)
if destination_path.exists():
print(f"Skipped existing file: {destination_path}")
else:
shutil.copy2(source_path, destination_path)
print(f"Copied: {destination_path}")
print("Original files are still in the inbox.")
else:
print("No files were copied.")
The sample files are created only when missing. The program previews the
destinations, waits for the exact word COPY, and never
overwrites or removes existing files.
Key takeaways
- Use
pathlibto inspect and build paths. - Preview source and destination paths before file operations.
- Use
copy2()to preserve originals while practicing. - Check that destinations do not exist before copying.