🌱 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 Curriculum — Select Module
1️⃣ Fundamentals
2️⃣ Data Types
3️⃣ Operators
4️⃣ Conditionals
5️⃣ Loops
6️⃣ Collections
7️⃣ Comprehensions
8️⃣ Functions
9️⃣ *args & **kwargs
🔟 Scope & Namespaces
1️⃣1️⃣ OOP
1️⃣2️⃣ Exceptions
1️⃣3️⃣ File Handling
1️⃣4️⃣ Modules & Packages
1️⃣5️⃣ Virtual Environments
1️⃣6️⃣ Standard Library
1️⃣7️⃣ Iterators & Iterables
1️⃣8️⃣ Generators
1️⃣9️⃣ Decorators
2️⃣0️⃣ Context Managers
2️⃣1️⃣ Lambda Functions
2️⃣2️⃣ Functional Programming
2️⃣3️⃣ Type Hints
2️⃣4️⃣ Dataclasses
2️⃣5️⃣ Testing
2️⃣6️⃣ Debugging
2️⃣7️⃣ Logging
2️⃣8️⃣ JSON & Data
2️⃣9️⃣ Regular Expressions
3️⃣0️⃣ Databases
🌱 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\ncharacter.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")
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")