Interview Q&A · Python · 15 questions in this topic

File Handling — Python Interview Q&A

All Python topics

Reading and writing files safely, context managers, text encodings, and the CSV/JSON work that shows up in almost every data question. Part of File Handling · 375 questions in the Python bank.

How do you open and close a file in Python?

Answer

Use the built-in open(path, mode) function to get a file object, and call.close() when finished to release the underlying operating system resource. In practice, you should almost always use a with statement instead of manual close calls (Q184).

Forgetting to close a file can leak file descriptors (a limited operating system resource) and, for writes, may leave data stuck in an internal buffer that was never actually flushed to disk.

Example

Example.pypython
# Manual approach -- works, but risky if an exception occurs before close()
f = open("notes.txt", "w")
f.write("Hello, file!")
f.close()
# Reading it back
f = open("notes.txt", "r")
content = f.read()
f.close()
print(content) # Hello, file!

💡 Even when demonstrating the manual open() / close() pattern, immediately flag that it's not what you'd actually use in real code — segueing into with (Q184) shows you know the idiomatic approach, not just the mechanical one.

What are the different file modes in Python?

Answer

The core modes are "r" (read, default), "w" (write, truncates existing content), "a" (append), and "x" (exclusive creation, fails if the file exists) — each can be combined with "b" for binary mode or "+" for simultaneous read/write access.

"w" mode is a common source of accidental data loss: opening an existing file in "w" mode immediately truncates it to zero bytes, even if you haven't written anything yet — there's no confirmation or undo.

Example

Example.pypython
open("file.txt", "r") # read text (default) -- errors if file doesn't exist
open("file.txt", "w") # write text -- ERASES existing content immediately
open("file.txt", "a") # append text -- adds to the end, preserves existing content
open("file.txt", "x")
# exclusive create -- raises FileExistsError if it already exists
open("image.png", "rb") # read binary
open("file.txt", "r+") # read AND write, without truncating

What is the difference between.read(),.readline(), and.readlines()?

Answer

.read() reads the entire file (or a specified number of characters/bytes) into a single string.readline() reads just one line at a time.readlines() reads the entire file into a list of lines. For large files, iterating over the file object directly (line by line) is more memory-efficient than any of these three.

This directly connects to 's discussion of generators and memory efficiency —.readlines() and.read() both load the entire file into memory at once, which is exactly what you want to avoid for very large files.

Example

Example.pypython
with open("data.txt") as f:
    content = f.read() # entire file as one string
with open("data.txt") as f:
    first_line = f.readline() # just the first line
with open("data.txt") as f:
    all_lines = f.readlines() # ['line1\n', 'line2\n', ...] -- full list in memory
with open("data.txt") as f:
    for line in f: # most memory-efficient -- one line at a time
        print(line.strip())

💡 If asked "how would you process a huge log file," explicitly reject.readlines() in your answer and reach for the direct for line in f: iteration — this is the same principle from, Q147, applied to the most basic file-reading question.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits