C
Python/Files/Lesson 24

pathlib — Modern File Paths (PEP 428)

15 min·theory
This chapter
2/2

pathlib — Modern File Paths (PEP 428)

🎯 After reading this lesson

Once you finish this lesson, you will be able to confidently do the following 3 things.

  • ✅ pathlib.Path as the modern replacement for os.path
  • ✅ with open() context manager + explicit encoding
  • ✅ Using the csv · json · yaml standard modules

Keep the learning goals as a checklist, and close the lesson once you can answer all of them.

pathlib — Code + Execution Results

pathlib.Path = OS-independent path handling. Standard library since Python 3.6+. os.path is the old way.


1. Creating Paths

python
from pathlib import Path

p = Path("data") / "user.json"
print(p)             # data\user.json (Win) or data/user.json (Mac)
print(type(p))       # <class 'pathlib.WindowsPath'> or PosixPath

Join paths with the / operator — separators are handled automatically per OS.


2. Extracting Information

python
p = Path("/home/user/photo.jpg")

print(p.name)        # photo.jpg
print(p.stem)        # photo
print(p.suffix)      # .jpg
print(p.parent)      # /home/user
print(p.parts)       # ('/', 'home', 'user', 'photo.jpg')

3. File Operations

python
p = Path("memo.txt")

# Check existence
if p.exists():
    print("exists")

# One-liner write/read
p.write_text("Hello!", encoding="utf-8")
content = p.read_text(encoding="utf-8")

# Info
print(p.is_file())       # True
print(p.is_dir())        # False
print(p.stat().st_size)  # File size (bytes)

4. Directory Operations

python
# Create a folder
Path("data").mkdir(exist_ok=True)

# All files inside a folder
for file in Path("data").iterdir():
    print(file)

# Pattern matching (glob)
for img in Path("photos").glob("*.jpg"):
    print(img)

# Recursive — including subfolders
for py in Path(".").rglob("*.py"):
    print(py)

5. Comparison with os.path

python
# ❌ Old way (os.path)
import os
path = os.path.join("data", "subdir", "file.txt")
extension = os.path.splitext(path)[1]
os.makedirs("data/subdir", exist_ok=True)

# ✅ pathlib
path = Path("data") / "subdir" / "file.txt"
extension = path.suffix
Path("data/subdir").mkdir(parents=True, exist_ok=True)

One-line Summary

Path(...) / "..." + .read_text() + .glob() — these three cover 90% of use cases. Graduate from os.path.

🐍 Try It Yourself — pathlib — Run It Directly

Try running the concepts above as actual code. The fastest way to learn is to change the values yourself and observe how they behave.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Knowing the concepts from this lesson lets you give specific instructions to AI. Instead of a vague "fix this," make a vocabulary-driven request — that is the starting point for saving tokens.

  • "Migrate this os.path code to pathlib"
  • "Add explicit encoding (encoding='utf-8') to this with open block"

Why This Reduces Tokens

When you don't know the concepts, you have to ask "What is that?" after receiving an AI response. That follow-up question is what consumes tokens. Learn the concept once, and the conversation ends in a single round.

Read this first: File I/O
pathlib — Modern File Paths (PEP 428) - Python