🐍 Python Beginner

What is file handling in Python?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Python basics — a prerequisite for any developer role.

Answer

Python has built-in file I/O capabilities. Open a file: f = open("file.txt", "r") — modes: "r" (read), "w" (write, overwrites), "a" (append), "x" (create, fails if exists), "b" (binary), "+" (read+write). Always use the with statement to ensure files are closed: with open("file.txt", "r") as f: content = f.read(). Read methods: read() (entire file), readline() (one line), readlines() (list of lines). Iterate line by line (memory efficient): for line in f. Write: f.write("text"), f.writelines(list). For paths, use pathlib: from pathlib import Path; Path("file.txt").read_text(). Binary files: open with "rb" or "wb" mode. Check existence: Path("file").exists().

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Python project, I used this when...' immediately makes your answer more credible and memorable.