Interview Q&A · Python · 15 questions in this topic
File Handling — Python Interview Q&A
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
# 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
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
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.
Why should you use with open() instead of manually calling open() / close()?
Answer
with open(.) guarantees the file is properly closed even if an exception occurs while it's being used — manual open() / close() requires you to remember (and correctly handle exceptions around) closing it yourself, which is easy to get wrong.
Under the hood, with relies on the file object being a context manager (Q185) — it calls.close() automatically via __exit__, regardless of whether the block completed normally or raised an exception.
Example
# Risky: if write() raises an exception, close() is NEVER called f = open("data.txt", "w") f.write(some_risky_computation()) # if this raises, the file stays open forever f.close() # Safe: guaranteed to close, even if an exception occurs inside the block with open("data.txt", "w") as f: f.write(some_risky_computation()) # file still gets closed properly on failure
💡 This is a specific, concrete application of the broader "context managers guarantee cleanup" principle from finally — connecting the two shows you see resource management as one consistent idea, not isolated syntax rules.
What are context managers, and how do they work?
Answer
A context manager is any object implementing __enter__ (called when entering a with block, its return value bound to the as variable) and __exit__ (called when leaving the block, whether normally or due to an exception) — this is the mechanism that powers with open(.).
__exit__ receives details about any exception that occurred (exc_type, exc_val, exc_tb) and can choose to suppress it by returning True — otherwise, the exception propagates normally after cleanup runs.
Example
class ManagedFile: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file # this is what gets bound to 'as f' def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() print("File automatically closed") return False # False (or None) -- don't suppress exceptions with ManagedFile("data.txt", "w") as f: f.write("Hello!") # "File automatically closed" prints here, even if write() had raised an exception
💡 Explaining what happens when __exit__ returns True versus False / None (suppressing versus propagating an exception) is a detail that clearly separates surface familiarity from real understanding of the protocol.
How would you implement your own custom context manager?
Answer
Either write a class implementing __enter__ / __exit__ (Q185), or use the simpler @contextlib.contextmanager decorator on a generator function, splitting setup and teardown code around a single yield.
The @contextmanager approach is often more concise for simple cases: everything before the yield acts like __enter__, the yielded value is what's bound to as, and everything after the yield acts like __exit__.
Example
from contextlib import contextmanager import time @contextmanager def timer(label): start = time.perf_counter() yield # code inside the 'with' block runs here elapsed = time.perf_counter() - start print(f"{label}: {elapsed:.4f}s") with timer("Processing"): total = sum(range(1_000_000)) # this runs while paused at yield # Output: "Processing: 0.0XXXs"
💡 Being able to write both the class-based (__enter__ / __exit__) and generator-based (@contextmanager) versions of the same context manager, and explain the trade-offs, is a strong, well-rounded answer.
What is the contextlib module, and what does @contextmanager do?
Answer
contextlib is the standard library module providing utilities for working with context managers — most notably the @contextmanager decorator (Q186), which turns a generator function into a full context manager without needing to write a class with __enter__ / __exit__.
contextlib also provides other useful tools: suppress() (a context manager that silently ignores specified exceptions), redirect_stdout(), and ExitStack (for dynamically managing a variable number of context managers at once).
Example
from contextlib import suppress # Instead of a full try/except block just to ignore one specific exception: with suppress(FileNotFoundError): import os os.remove("might_not_exist.txt") # silently does nothing if the file is missing # Equivalent to: # try: # os.remove("might_not_exist.txt") # except FileNotFoundError: # pass
💡 Mentioning contextlib.suppress() as a cleaner alternative to a try / except / pass block for a single expected exception type is a nice, concrete example of writing more idiomatic Python.
How do you read and write CSV files in Python?
Answer
Use the standard library's csv module — csv.reader / csv.writer for simple row-based access, or csv.DictReader / csv.DictWriter when you want each row represented as a dictionary keyed by column header.
DictReader / DictWriter are usually preferred in real code because accessing columns by name (row["email"]) is far more readable and resilient to column reordering than accessing by numeric index (row[3]).
Example
import csv # Writing with DictWriter with open("users.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=["name", "age"]) writer.writeheader() writer.writerow({"name": "Ana", "age": 30}) writer.writerow({"name": "Ben", "age": 25}) # Reading with DictReader with open("users.csv") as f: reader = csv.DictReader(f) for row in reader: print(row["name"], row["age"]) # Ana 30 / Ben 25
💡 Mention the newline="" argument when opening a file for csv.writer / DictWriter on some platforms — it's a small, commonly forgotten detail (avoiding extra blank lines on Windows) that signals real hands-on CSV experience.
How do you read and write JSON files in Python?
Answer
Use the standard library's json module: json.dump() / json.load() for working directly with file objects, and json.dumps() / json.loads() for converting to/from JSON-formatted strings in memory.
JSON only supports a limited set of types natively (strings, numbers, booleans, null, lists, and objects/dicts) — Python objects like datetime, sets, or custom classes aren't JSON-serializable by default and require custom conversion logic (an encoder / decoder, or converting to a supported type first).
Example
import json data = {"name": "Ana", "age": 30, "active": True} # Writing to a file with open("user.json", "w") as f: json.dump(data, f, indent=2) # Reading from a file with open("user.json") as f: loaded = json.load(f) print(loaded) # {'name': 'Ana', 'age': 30, 'active': True} # In-memory string conversion json_string = json.dumps(data) parsed_back = json.loads(json_string)
💡 If asked to serialize a datetime object, mention that you'd either convert it to an ISO-format string beforehand (.isoformat()) or pass a custom default= function to json.dump() — this shows you know JSON's type limitations, not just the happy path.
What is serialization, and why is it needed?
Answer
Serialization is converting an in-memory object into a format (bytes or text) that can be stored in a file, sent over a network, or otherwise persisted — with deserialization being the reverse process of reconstructing the original object from that format.
Different serialization formats trade off different properties: JSON is human-readable and language-agnostic (making it ideal for APIs and configuration), while binary formats like pickle (Q191) preserve richer Python-specific type information but sacrifice portability and readability.
Example
import json config = {"debug": True, "max_connections": 100} serialized = json.dumps(config) # in-memory Python dict -> JSON string print(serialized) # '{"debug": true, "max_connections": 100}' print(type(serialized)) # <class 'str'> deserialized = json.loads(serialized) # JSON string -> Python dict again print(deserialized == config) # True
💡 Frame serialization around its two core purposes — persistence (saving state between program runs) and communication (sending data between processes, services, or languages) — rather than a single vague "converting data" definition.
What is pickling, and how does it differ from JSON serialization?
Answer
Pickling (via the pickle module) serializes nearly any Python object — including custom class instances, functions, and complex nested structures — into a Python-specific binary format. JSON only supports a limited set of universal data types and is both human-readable and cross-language compatible; pickle is neither.
Choose JSON when you need interoperability (an API consumed by non-Python clients, human-readable config files) and pickle only for Python-to-Python persistence where preserving exact object structure matters more than portability or safety.
Example
import pickle import json class Point: def __init__(self, x, y): self.x, self.y = x, y p = Point(1, 2) # Pickle can serialize the custom object directly with open("point.pkl", "wb") as f: # note: binary mode ("wb") required pickle.dump(p, f) with open("point.pkl", "rb") as f: loaded_point = pickle.load(f) print(loaded_point.x, loaded_point.y) # 1 2 -- fully reconstructed custom object # JSON CANNOT serialize a custom object directly: # json.dumps(p) # TypeError: Object of type Point is not JSON serializable
💡 "JSON for interoperability and readability, pickle for Python-only convenience with arbitrary objects" is the concise framing interviewers are listening for — always pair it with the critical security caveat from Q192.
What are the security risks of unpickling untrusted data?
Answer
Unpickling data is not just "parsing" it — the pickle format can encode instructions that execute arbitrary code during deserialization. Loading a pickle file from an untrusted or unauthenticated source can lead to full remote code execution, making it a serious security vulnerability if misused.
This is a critical distinction from JSON: json.loads() on malicious input can, at worst, produce weird data or a parsing error — it cannot execute code. pickle.load() on malicious input can run arbitrary code on your machine, which is why the official Python documentation explicitly warns never to unpickle data from an untrusted or unauthenticated source.
Example
import pickle # NEVER do this with data from an untrusted source (a network request, # user upload, unauthenticated queue message, etc.): # untrusted_data = receive_from_network() # obj = pickle.loads(untrusted_data) # could execute arbitrary attacker code! # Safe pattern: only unpickle data your own application created and controls, # e.g., an internal cache file never exposed to external input. with open("internal_cache.pkl", "rb") as f: cached_data = pickle.load(f) # fine -- trusted, internally generated file
What is the difference between text mode and binary mode when opening files?
Answer
Text mode (the default) automatically decodes file bytes into str using a specified (or platform-default) encoding, and handles newline translation. Binary mode ("b" suffix, e.g., "rb") reads/writes raw bytes with no decoding or newline translation at all.
Binary mode is required for non-text files (images, audio, pickled data, any format not meant to be interpreted as encoded text) — attempting to open such a file in text mode often raises a UnicodeDecodeError, since the raw bytes usually aren't valid text in whatever encoding Python assumes.
Example
# Text mode: automatically decodes to str with open("notes.txt", "r", encoding="utf-8") as f: content = f.read() print(type(content)) # <class 'str'> # Binary mode: raw bytes, no decoding at all with open("image.png", "rb") as f: content = f.read() print(type(content)) # <class 'bytes'> # Opening a binary file in text mode often fails: # with open("image.png", "r") as f: # f.read() # UnicodeDecodeError -- image bytes aren't valid UTF-8 text
💡 Always mention specifying encoding="utf-8" explicitly for text mode in real code — relying on the platform's default encoding (which can differ between Windows and Linux/macOS) is a classic source of "works on my machine" bugs.
What are common file-handling mistakes, and how do you avoid them?
Answer
The most common mistakes are: forgetting to use with (risking unclosed files), opening a file in "w" mode when "a" was intended (accidentally erasing data), not specifying an encoding, and loading an entire large file into memory when a lazy, line-by-line approach would work.
Most of these mistakes are individually small but compound in production systems — an unclosed file here, an unspecified encoding there, and eventually you have intermittent, hard-to-reproduce bugs (resource exhaustion, encoding-dependent crashes on a different machine) that are painful to trace back to their source.
Example
# Mistake 1: no context manager -- file may never close if an exception occurs f = open("data.txt") data = f.read() f.close() # Mistake 2: "w" mode used where "a" (append) was actually intended with open("log.txt", "w") as f: # WIPES the existing log every single run! f.write("New entry\n") # Mistake 3: no explicit encoding -- behavior can differ across platforms with open("data.txt") as f: # relies on platform default encoding content = f.read() # All fixed: with open("log.txt", "a", encoding="utf-8") as f: # with, correct mode, explicit encoding f.write("New entry\n")
💡 If this question comes up, structure your answer as a short checklist (context manager, correct mode, explicit encoding, appropriate reading strategy for file size) — it reads as more thorough and organized than a rambling list of anecdotes.
How would you handle very large files efficiently in Python?
Answer
Never load the whole file into memory at once — iterate line-by-line for text files (the file object is already a lazy iterator), or read in fixed-size chunks for binary data, combining this with generators to build memoryefficient processing pipelines.
For structured large datasets (very large CSVs, for example), it's also worth considering whether a streaming/ chunked library approach (like pandas' chunksize parameter, or a dedicated database) is more appropriate than hand-rolling file iteration — the right tool depends on what you ultimately need to do with the data, not just how you read it.
Example
# Text: line-by-line, constant memory usage regardless of file size def process_large_text_file(path): with open(path, encoding="utf-8") as f: for line in f: # lazy -- one line in memory at a time yield line.strip() # Binary: fixed-size chunks, useful for non-line-oriented data def process_large_binary_file(path, chunk_size=1024 * 1024): # 1 MB chunks with open(path, "rb") as f: while chunk := f.read(chunk_size): yield chunk # Combine with a processing pipeline (Q150 pattern): error_lines = (line for line in process_large_text_file("app.log") if "ERROR" in line)
💡 This question is a direct, practical culmination of (generators/laziness) and 9 (file handling) together — explicitly connecting the two in your answer ("this is the same lazy-iteration principle as generators, applied to file I/O") demonstrates you see how these concepts compose in real systems.
Recommended resourcesAffiliate links · may earn us a commission