
Python
Learn to work with file paths safely across Windows, Mac, and Linux.
File paths show the location of files in your system.
# Absolute path (full location from root)
"/Users/alice/Documents/data.txt" # macOS/Linux
"C:\\Users\\alice\\Documents\\data.txt" # Windows
# Relative path (from current directory)
"data.txt" # File in current directory
"reports/monthly.txt" # In subdirectory`pathlib` handles path differences across operating systems automatically.
from pathlib import Path
# Create path object
file_path = Path("data.txt")
# Works on all operating systems
file_path = Path("reports") / "2024" / "sales.txt"
# Check if file exists
if file_path.exists():
print("File found!")
# Read file
content = file_path.read_text()
# Write file
file_path.write_text("New data")from pathlib import Path
# Project structure (works on all OS)
project_dir = Path(__file__).parent
data_dir = project_dir / "data"
output_dir = project_dir / "output"
# Create directories if needed
data_dir.mkdir(parents=True, exist_ok=True)
output_dir.mkdir(parents=True, exist_ok=True)
# Read from data directory
input_file = data_dir / "input.csv"
if input_file.exists():
content = input_file.read_text()
# Write to output directory
output_file = output_dir / "results.txt"
output_file.write_text("Analysis complete")| Operation | Purpose | Example |
|---|---|---|
| `Path(name)` | Create path | `Path("data.txt")` |
| `path / "file"` | Join paths | `dir / "file.txt"` |
| `path.exists()` | Check if exists | `if path.exists():` |
| `path.read_text()` | Read entire file | `content = path.read_text()` |
| `path.write_text()` | Write to file | `path.write_text("data")` |
| `path.mkdir()` | Create directory | `path.mkdir(parents=True)` |
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward