← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Pathlib

Topic: System

Advertisement

Introduction

Pathlib provides object-oriented filesystem paths, cleaner than os.path.

Basic Path Operations

from pathlib import Path

p = Path(".")

# Traversing
p / "subdir" / "file.txt"

# Reading and writing
p.write_text("Hello")
content = p.read_text()

# Glob patterns
list(p.glob("*.py"))
list(p.glob("**/*.txt"))

Path Properties

from pathlib import Path

p = Path("example.txt")

p.name       # 'example.txt'
p.stem       # 'example'
p.suffix     # '.txt'
p.parent     # Parent directory
p.parts      # Path components

p.exists()
p.is_file()
p.is_dir()

Creating Paths

from pathlib import Path

# Absolute paths
Path("/home/user/file")
Path.cwd()       # Current working directory
Path.home()      # Home directory

# Home-relative
Path("~/documents").expanduser()

Practice Problems

  1. Navigate directory tree with pathlib
  2. Find all Python files recursively
  3. Create file backup with new extension
  4. Walk directory hierarchy
  5. Resolve file paths safely

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →