Manage Files and Folders with Python: pathlib and shutil
pathlib is Python's modern, object-oriented approach to file paths (since 3.4), cross-platform by design. shutil adds high-level operations: copy, move and delete entire trees.
pathlib — Paths as Objects
from pathlib import Path
path = Path("/home/user/documents/report.pdf")
print(path.name) # report.pdf
print(path.stem) # report
print(path.suffix) # .pdf
print(path.parent) # /home/user/documents
print(path.exists()) # True/False
# Relative and absolute paths
rel = Path("data/files.csv")
abs_path = rel.resolve()
# Build paths (cross-platform)
base = Path.home()
folder = base / "Documents" / "Project"
file = folder / "config.json"
print(file)
Create, List and Delete
from pathlib import Path
import shutil
# Create folder (and parents)
folder = Path("my_project/data/raw")
folder.mkdir(parents=True, exist_ok=True)
# Create and write file
file = Path("my_project/README.txt")
file.write_text("This is the project README.", encoding="utf-8")
# Read file
content = file.read_text(encoding="utf-8")
print(content)
# List folder contents
for item in Path("my_project").iterdir():
kind = "DIR" if item.is_dir() else "FILE"
print(f" [{kind}] {item.name}")
# Delete file
file.unlink()
# Delete empty folder
Path("my_project/data/raw").rmdir()
# Delete folder with contents
shutil.rmtree("my_project/data")
Find Files with glob and rglob
from pathlib import Path
base = Path("my_project")
# All .py files (non-recursive)
for f in base.glob("*.py"):
print(f.name)
# All .py files (recursive)
for f in base.rglob("*.py"):
print(f.relative_to(base))
# Multiple extensions
for f in base.rglob("*"):
if f.suffix in {".jpg", ".png", ".gif"}:
print(f"Image: {f}")
# Count files by extension
from collections import Counter
count = Counter(f.suffix.lower() for f in base.rglob("*") if f.is_file())
for ext, n in count.most_common():
print(f" {ext or '(no ext)'}: {n} files")
Copy and Move Files
import shutil
from pathlib import Path
# Copy file (with metadata)
shutil.copy2("source.pdf", "destination.pdf")
shutil.copy2("source.pdf", "dest_folder/")
# Copy entire folder
shutil.copytree("source_folder", "backup_folder",
ignore=shutil.ignore_patterns("*.tmp", "__pycache__", "*.pyc"))
# Move file or folder
shutil.move("old_name.pdf", "new_name.pdf")
shutil.move("source_folder", "new_location/source_folder")
# Rename with pathlib
Path("old_file.txt").rename("new_file.txt")
Auto-Organize Files by Type
from pathlib import Path
import shutil
TYPES = {
"images": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg"},
"videos": {".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv"},
"audio": {".mp3", ".wav", ".ogg", ".flac", ".aac", ".m4a"},
"documents": {".pdf", ".docx", ".xlsx", ".pptx", ".txt", ".csv"},
"archives": {".zip", ".rar", ".7z", ".tar", ".gz"},
}
def organize_folder(folder):
folder = Path(folder)
moved = 0
for file in folder.iterdir():
if not file.is_file(): continue
ext = file.suffix.lower()
for category, extensions in TYPES.items():
if ext in extensions:
dest = folder / category
dest.mkdir(exist_ok=True)
shutil.move(str(file), dest / file.name)
print(f" {file.name} -> {category}/")
moved += 1
break
print(f"Organized {moved} files")
organize_folder("Downloads/")
Folder Size and Statistics
from pathlib import Path
def folder_stats(folder):
folder = Path(folder)
all_items = list(folder.rglob("*"))
total_bytes = sum(f.stat().st_size for f in all_items if f.is_file())
total_files = sum(1 for f in all_items if f.is_file())
total_folders = sum(1 for f in all_items if f.is_dir())
print(f"Folder: {folder}")
print(f"Files: {total_files}")
print(f"Folders: {total_folders}")
print(f"Size: {total_bytes/1024/1024:.2f} MB")
largest = sorted(
(f for f in all_items if f.is_file()),
key=lambda f: f.stat().st_size,
reverse=True
)[:5]
print("\nTop 5 largest files:")
for f in largest:
print(f" {f.stat().st_size//1024:>8} KB {f.relative_to(folder)}")
folder_stats("my_project")
Additional Resource
For converting files between different formats without any coding, use KaijuConverter — free and no registration required.
Related conversions
Frequent conversions across the catalogue: