Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/File Paths

🗂️ Working with File Paths — Cross-Platform File Access

Learn to work with file paths safely across Windows, Mac, and Linux.


🎯 Understanding File Paths

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

💡 Using pathlib for Portable Code

`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")

🎨 Real-World Example: Cross-Platform Project

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")

📊 Path Operations

OperationPurposeExample
`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)`

🔑 Key Takeaways

  • ✅ Use `pathlib.Path` for portable paths
  • ✅ Works on Windows, Mac, and Linux
  • ✅ Use `/` operator to join paths
  • ✅ Check `exists()` before reading
  • ✅ Create directories with `mkdir()`

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn