Loading exercise...

Exercise: Organize Files by Extension

Avatar image for Ziggy

Ziggy on Oct. 25, 2026

I used glob and move() i can’t remember you are explaining replace()

from pathlib import Path


def organize_by_extension(directory):
    """Move files into subdirectories based on their extension."""
    folder = Path(directory)
    for file in folder.glob('*.*'):
        ext = file.suffix[1:]
        if file.is_file() and file.suffix:
            (folder / ext).mkdir(parents=True, exist_ok=True)
            source = folder / file.name
            destination = folder / ext / file.name
            source.move(destination)

Become a Member to join the conversation.