🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#pathlib#files

pathlib — Modern File Path Handling

Use pathlib.Path instead of os.path for cleaner code.


from pathlib import Path

# Current directory
current = Path(".")
home = Path.home()      # /Users/username

# Building paths (works on all OS)
data_dir = Path("data")
file = data_dir / "users" / "alice.json"  # uses / operator!

# File info
file.exists()       # True/False
file.is_file()      # True/False
file.is_dir()       # True/False
file.suffix         # ".json"
file.stem           # "alice"
file.name           # "alice.json"
file.parent         # data/users

Reading/writing:

content = file.read_text()       # read as string
bytes = file.read_bytes()        # read as bytes
file.write_text("Hello")        # write string
file.mkdir(parents=True, exist_ok=True)  # create dirs

Listing files:

for f in Path(".").iterdir():
    print(f)

for f in Path(".").glob("*.py"):  # pattern matching
    print(f)

YouTube • Top 10
Python Programming: The pathlib Module
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: The pathlib Module
Tap to View ›

Reference:

Wikipedia: Path

image for linkhttps://en.wikipedia.org/wiki/Path_(computing)

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT