- Create and delete files and directories
- Copy, move, and rename files
- Handle file operations safely with error handling
- Build practical file management utilities
File Management
You've learned to read and write files. Now it's time to become the boss of your file system! File management means creating folders, organizing files, copying backups, cleaning up old data, and automating the tedious tasks you'd normally do manually in your file explorer.
Think of Python as your personal assistant that can organize thousands of files in seconds, create backup systems, and keep your projects tidy – all automatically.
Creating Directories
Basic Directory Creation
from pathlib import Path
# Create a single directory
folder = Path("new_folder")
folder.mkdir() # Creates new_folder/
# What if it already exists? Error!
# folder.mkdir() # FileExistsError!
# Safe creation with exist_ok
folder.mkdir(exist_ok=True) # No error if exists
Creating Nested Directories
from pathlib import Path
# Create parent directories too
deep_path = Path("project/data/raw/2024")
deep_path.mkdir(parents=True, exist_ok=True)
# This creates:
# project/
# data/
# raw/
# 2024/
Visual: mkdir Options
mkdir() Options
path.mkdir()
• Creates single directory
• Error if parent doesn't exist
• Error if already exists
path.mkdir(parents=True)
• Creates all parent directories
• Error if already exists
path.mkdir(exist_ok=True)
• Creates single directory
• No error if already exists
path.mkdir(parents=True, exist_ok=True) ← RECOMMENDED
• Creates all parent directories
• No error if already exists
Deleting Files and Directories
Deleting Files
from pathlib import Path
file = Path("old_file.txt")
# Check before deleting
if file.exists():
file.unlink() # Delete the file
print("File deleted!")
# Or use missing_ok (Python 3.8+)
file.unlink(missing_ok=True) # No error if doesn't exist
Deleting Directories
from pathlib import Path
import shutil
# Delete EMPTY directory
empty_dir = Path("empty_folder")
empty_dir.rmdir() # Only works if empty!
# Delete directory WITH contents
full_dir = Path("folder_with_files")
shutil.rmtree(full_dir) # Deletes everything inside!
Safety Warning
DELETION WARNING
shutil.rmtree() is PERMANENT and DANGEROUS!
• No recycle bin / trash
• No undo
• Deletes everything recursively
ALWAYS:
Double-check the path
Print before deleting
Ask for confirmation in scripts
Consider moving to a "trash" folder instead
Copying Files
Use shutil for copying operations:
import shutil
from pathlib import Path
# Copy a file
source = Path("original.txt")
destination = Path("backup/original_copy.txt")
# Make sure destination folder exists
destination.parent.mkdir(parents=True, exist_ok=True)
# Copy the file
shutil.copy(source, destination) # Copy file only
shutil.copy2(source, destination) # Copy file + metadata (timestamps)
Copying Directories
import shutil
from pathlib import Path
source_dir = Path("my_project")
backup_dir = Path("backups/my_project_backup")
# Copy entire directory tree
shutil.copytree(source_dir, backup_dir)
# If destination exists, handle it (Python 3.8+)
shutil.copytree(source_dir, backup_dir, dirs_exist_ok=True)
Moving and Renaming
Renaming Files
from pathlib import Path
old_name = Path("draft.txt")
new_name = Path("final.txt")
old_name.rename(new_name)
print(f"Renamed to {new_name}")
Moving Files
from pathlib import Path
import shutil
# Using pathlib (same directory or simple moves)
file = Path("report.pdf")
file.rename(Path("archive/report.pdf"))
# Using shutil (more robust, works across drives)
shutil.move("source.txt", "destination/source.txt")
Batch Renaming
from pathlib import Path
def batch_rename(folder, old_prefix, new_prefix):
"""Rename all files with a certain prefix."""
folder = Path(folder)
for file in folder.glob(f"{old_prefix}*"):
new_name = file.name.replace(old_prefix, new_prefix)
file.rename(file.parent / new_name)
print(f"Renamed: {file.name} → {new_name}")
# Rename all "IMG_" files to "Photo_"
batch_rename("vacation_photos", "IMG_", "Photo_")
Practical Examples
Example 1: Project Setup
from pathlib import Path
def create_project_structure(project_name):
"""Create a standard project folder structure."""
base = Path(project_name)
folders = [
base / "src",
base / "tests",
base / "data" / "raw",
base / "data" / "processed",
base / "docs",
base / "output"
]
for folder in folders:
folder.mkdir(parents=True, exist_ok=True)
print(f"Created: {folder}")
# Create empty files
(base / "README.md").touch()
(base / "src" / "__init__.py").touch()
print(f"\n Project '{project_name}' created!")
create_project_structure("my_new_project")
Example 2: Backup System
from pathlib import Path
from datetime import datetime
import shutil
def create_backup(source_folder):
"""Create a timestamped backup of a folder."""
source = Path(source_folder)
if not source.exists():
print(f"Source folder '{source}' not found!")
return None
# Create backup name with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_name = f"{source.name}_backup_{timestamp}"
backup_path = source.parent / "backups" / backup_name
# Create backup
backup_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source, backup_path)
print(f" Backup created: {backup_path}")
return backup_path
create_backup("important_project")
Example 3: Cleanup Old Files
from pathlib import Path
from datetime import datetime, timedelta
def cleanup_old_files(folder, days_old=30, dry_run=True):
"""Delete files older than specified days."""
folder = Path(folder)
cutoff = datetime.now() - timedelta(days=days_old)
deleted = []
for file in folder.rglob("*"):
if file.is_file():
modified_time = datetime.fromtimestamp(file.stat().st_mtime)
if modified_time < cutoff:
if dry_run:
print(f"Would delete: {file}")
else:
file.unlink()
print(f"Deleted: {file}")
deleted.append(file)
print(f"\n{'Would delete' if dry_run else 'Deleted'} {len(deleted)} files")
return deleted
# First do a dry run to see what would be deleted
cleanup_old_files("temp_files", days_old=7, dry_run=True)
# Then actually delete (set dry_run=False)
# cleanup_old_files("temp_files", days_old=7, dry_run=False)
Key Takeaways
Remember These Points
Create directories:
path.mkdir(parents=True, exist_ok=True)
Delete files: path.unlink()
Delete empty dirs: path.rmdir()
Delete with contents: shutil.rmtree() CAREFUL!
Copy files: shutil.copy(src, dst)
Copy dirs: shutil.copytree(src, dst)
Move/rename: path.rename(new) or shutil.move()
Always check .exists() before operations
Use dry_run for dangerous operations
Module Complete!
Congratulations! You've mastered file handling in Python!
You can now:
- Read and write files with confidence
- Navigate paths across any operating system
- Create, copy, move, and delete files and folders
- Build practical file management tools
In the next module, you'll learn about Error Handling – how to write robust code that gracefully handles problems!
