File Handling in Python — Python Technical Interview Questions & Answers
File Handling in Python
File Handling in Python
- File handling is reading and writing disk files. open(path, mode) with "r" read, "w" write (erases existing), "a" append, "rb" binary. Prefer with open(...) as f: so the file closes even if an error happens. read(), readline(), readlines() for input. write() / writelines() for output.
- Trap: "w" on a marks file you meant to read — content gone. Always mention with in the viva. Then one tiny write of "Asha,90\n" and read it back.
- File Handling in Python — output: Asha then Pune. StringIO is the same read pattern as a real file, and this script always runs.
with open(...) as f
│ read / write
▼
auto closeTechnical Interview Tip: with open as best practice.
Code Examples for File Handling in Python
Example
# File idea
from io import StringIO
f = StringIO("Asha\nPune")
print(f.readline().strip())
print(f.readline().strip())
File Handling in Python — output: Asha then Pune. StringIO is the same read pattern as a real file, and this script always runs.
How to Explain File Handling in Python to an Interviewer
Explain File Handling as if you are teaching a junior — definition, then one tiny script.
open + modes. with auto-close. "w" overwrites.
What does the example print, and why?
File Handling in Python — output: Asha then Pune
What mistake do freshers make with File Handling?
read / write helpers.