Python reads and writes files with built-in open() and context managers. Text mode handles encoding; binary mode returns bytes—essential for images and compressed data.
Reading and writing text
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
with open("notes.txt", encoding="utf-8") as f:
content = f.read()
with ensures files close even when exceptions occur—like using in C# or try-with-resources in Java.
Line iteration
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.rstrip())
Important interview questions and answers
- Q: Why use with open?
A: Guarantees file closure via context manager protocol—prevents descriptor leaks. - Q: Text vs binary mode?
A: Text decodes/encodes with encoding; binary reads raw bytes without newline translation.
Self-check
- What mode writes a new text file?
- Why specify encoding="utf-8"?
Tip: Always specify encoding="utf-8" for text files—avoid platform-default surprises.
Interview prep
- Why with open?
Context manager closes file even on exceptions—prevents descriptor leaks.
- Text vs binary mode?
Text returns str with encoding; binary returns bytes without newline translation.