🗂️ Handling File Paths
Python provides powerful tools for working with file and directory paths. The modern pathlib
module and traditional os.path
module offer cross-platform path handling.
from pathlib import Path
# Basic path operations
file_path = Path('documents/report.txt')
print(f"File name: {file_path.name}")
print(f"Parent directory: {file_path.parent}")
print(f"File exists: {file_path.exists()}")
🎯 Path Modules
Python offers two main approaches for path handling.
Path Creation and Properties
from pathlib import Path
# Creating paths
file_path = Path('documents/reports/annual.txt')
print(f"Path: {file_path}")
# Path properties
print(f"Name: {file_path.name}")
print(f"Suffix: {file_path.suffix}")
print(f"Stem: {file_path.stem}")
print(f"Parent: {file_path.parent}")
print(f"Parts: {file_path.parts}")
Path Operations
# Path operations and checks
print(f"Absolute path: {file_path.absolute()}")
print(f"Exists: {file_path.exists()}")
print(f"Is file: {file_path.is_file()}")
print(f"Is directory: {file_path.is_dir()}")
# Creating new paths from existing
new_path = file_path.with_suffix('.pdf')
print(f"New path: {new_path}")
backup_path = file_path.with_name('backup_' + file_path.name)
print(f"Backup path: {backup_path}")
Path Joining and Navigation
# Joining paths
base_dir = Path('projects')
project_path = base_dir / 'my_project' / 'src' / 'main.py'
print(f"Joined path: {project_path}")
# Current directory operations
current_dir = Path.cwd()
home_dir = Path.home()
print(f"Current directory: {current_dir}")
print(f"Home directory: {home_dir}")
🔍 Advanced Path Operations
Python allows sophisticated path manipulation and file system operations.
Directory Operations
from pathlib import Path
# Directory creation and structure
project_dir = Path('my_project')
# Create directory structure
(project_dir / 'src').mkdir(parents=True, exist_ok=True)
(project_dir / 'tests').mkdir(exist_ok=True)
(project_dir / 'docs').mkdir(exist_ok=True)
print(f"Created directory structure in {project_dir}")
# List directory contents
for item in project_dir.iterdir():
if item.is_dir():
print(f"Directory: {item.name}")
else:
print(f"File: {item.name}")
File Pattern Matching
# Find files with patterns
py_files = list(project_dir.rglob('*.py'))
print(f"Python files: {py_files}")
txt_files = list(project_dir.glob('**/*.txt'))
print(f"Text files: {txt_files}")
# Find files in specific directory
src_files = list((project_dir / 'src').glob('*'))
print(f"Files in src: {src_files}")
Path Validation and Safe Operations
import shutil
# Path validation and normalization
def validate_path(path_str):
try:
path = Path(path_str)
# Resolve to absolute path
resolved = path.resolve()
print(f"Resolved path: {resolved}")
return resolved
except Exception as e:
print(f"Invalid path: {e}")
return None
# Safe file operations
def safe_file_operation(source, destination):
source_path = Path(source)
dest_path = Path(destination)
if not source_path.exists():
print(f"Source file {source} does not exist")
return False
# Create destination directory if needed
dest_path.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.copy2(source_path, dest_path)
print(f"Copied {source} to {destination}")
return True
except Exception as e:
print(f"Copy failed: {e}")
return False
validate_path('../documents/file.txt')
Cross-Platform and Relative Paths
import os
# Cross-platform path handling
def get_config_path():
"""Get platform-appropriate config directory"""
if os.name == 'nt': # Windows
return Path.home() / 'AppData' / 'Local' / 'MyApp'
else: # Unix-like
return Path.home() / '.config' / 'myapp'
# Working with relative paths
def make_relative_path(file_path, base_path):
"""Make file_path relative to base_path"""
try:
return Path(file_path).relative_to(base_path)
except ValueError:
return Path(file_path)
config_dir = get_config_path()
print(f"Config directory: {config_dir}")
rel_path = make_relative_path('/home/user/projects/file.py', '/home/user')
print(f"Relative path: {rel_path}")
📋 Path Methods Reference Table
Method | Purpose | Example |
---|---|---|
.name | File name with extension | 'report.txt' |
.stem | File name without extension | 'report' |
.suffix | File extension | '.txt' |
.parent | Parent directory | Path('docs') |
.parts | Path components | ('documents', 'report.txt') |
.exists() | Check if path exists | True/False |
.is_file() | Check if it's a file | True/False |
.is_dir() | Check if it's a directory | True/False |
.mkdir() | Create directory | Creates directory |
.iterdir() | List directory contents | Iterator of paths |
.glob() | Find files by pattern | List of matching paths |
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.