File I/O
File I/O
🎯 After reading this lesson
By the end of this lesson, you will be able to confidently do the following 3 things.
- ▸✅
pathlib.Pathas the modern replacement foros.path - ▸✅
with open()context manager + explicit encoding - ▸✅ Using the
csv,json, andyamlstandard modules
Keep the learning objectives as a checklist and close the lesson once you can answer all of them.
6 File I/O Patterns — Code + Output
Reading and writing files = saving data to disk or loading it back. The foundation of every program.
1. Writing a Text File
"w" = write (overwrites). Existing content is lost. "a" = append (adds to end).
⚠️ For non-ASCII text, encoding="utf-8" is required. Without it, the output will be garbled on Windows.
2. Reading a Text File
3. The with Statement — Auto Close
with is the Python standard for resource management. Always use it.
4. Reading and Writing JSON
ensure_ascii=False — saves non-ASCII characters as-is (without it, they become \uXXXX escapes).indent=2 — pretty-prints for human readability.
5. Reading and Writing CSV
⚠️ newline="" — avoids extra blank line issues on Windows.
6. pathlib — Modern Path Handling (Python 3.6+)
os.path.join is the old way — pathlib is the modern recommended approach.
One-Line Summary
Key takeaway: Always use with + encoding="utf-8". Without them, you risk garbled text or forgotten close() calls.
🐍 Try It Yourself — File I/O
🤖 Try Asking AI Like This
Knowing the concepts in this lesson lets you give AI specific instructions. Not a vague 'fix this' but a vocabulary-driven request — that is where token savings begin.
- ▸'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 does that mean?' after every response. That follow-up question is what burns tokens. Learn the concept once, and the conversation ends in a single turn.