🌱 Junior Track 13 of 13

13. File Handling & pathlib

Work with files cleanly: `open()`, context managers (`with`), reading/writing/appending, text vs. binary modes, file paths, and modern `pathlib.Path` operations.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 13 — FILE HANDLING & PATHLIB
# ==============================================================================

from pathlib import Path

# 1. Writing Text File using Context Manager ('w' mode)
file_path = Path("demo_notes.txt")

with open(file_path, mode="w", encoding="utf-8") as file:
    file.write("Line 1: Python Masterclass\n")
    file.write("Line 2: Context Managers close files automatically!\n")

# 2. Appending Lines ('a' mode)
with open(file_path, mode="a", encoding="utf-8") as file:
    file.write("Line 3: Appended content successfully.\n")

# 3. Reading Text File ('r' mode)
with open(file_path, mode="r", encoding="utf-8") as file:
    content = file.read()
    print("--- File Content via open() ---")
    print(content)

# 4. Modern pathlib.Path Operations
path_obj = Path("pathlib_demo.txt")
path_obj.write_text("Clean & elegant file I/O with pathlib!", encoding="utf-8")

if path_obj.exists():
    text = path_obj.read_text(encoding="utf-8")
    print(f"[PATHLIB READ] {text}")
    print(f"[INFO] File size: {path_obj.stat().st_size} bytes")

# 5. Writing and Reading Binary Files ('wb' / 'rb')
bin_path = Path("data.bin")
binary_payload = b"\x00\x01\x02\xFF\xFE"

with open(bin_path, mode="wb") as bfile:
    bfile.write(binary_payload)

with open(bin_path, mode="rb") as bfile:
    data = bfile.read()
    print(f"[BINARY READ] {data}")

# Cleanup generated demo files
file_path.unlink()
path_obj.unlink()
bin_path.unlink()
🌱 Junior Track 13 Master Reference

13. Python File Handling & pathlib Reference

1️⃣ File Open Modes Cheat Sheet

Mode Description Behavior if File Exists Behavior if File Missing
'r' Read text (default). Reads from start. Raises FileNotFoundError.
'w' Write text. Truncates / overwrites file. Creates new empty file.
'a' Append text. Appends data to end. Creates new file.
'rb' / 'wb' Binary Read / Write. Processes raw bytes. Same as text modes.

2️⃣ Reading Methods (`read`, `readline`, `readlines`)

  • file.read(): Reads the entire file content as a single string.
  • file.readline(): Reads a single line up to the newline \n character.
  • file.readlines(): Reads all lines and returns a Python list of strings.
  • for line in file:: Most memory-efficient way to iterate through large files line by line.

3️⃣ Modern Path Handling with `pathlib.Path`

from pathlib import Path

p = Path("logs/app.log")
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("[INFO] Server started successfully", encoding="utf-8")
content = p.read_text(encoding="utf-8")

⭐ Rate Track 13: File I/O & Pathlib (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 12. Exceptions 🌱 Junior Hub 14. Modules & Packages →