Interview Questions: File Handling & CSV
File handling is one of the fastest ways an interviewer can tell if someone has written real, production-facing code or only ever worked with in-memory data. This set covers why with is the standard way to open a file and what happens without it, the data-loss risk of confusing "r"/"w"/"a" modes, why FileNotFoundError should be caught specifically rather than with a bare except, why hand-splitting a CSV line on commas breaks on quoted fields, when csv.DictReader's extra readability is worth it over csv.reader, text mode vs. binary mode, why relative paths can silently point to the wrong file depending on where a script runs from, and how these pieces combine in real-world log analysis.
1 Why is the with statement preferred over manually calling open() and close()?
with open("file.txt") as f: guarantees the file gets closed the instant its indented block ends — even if an exception is raised partway through that block. Manually writing f = open(...) followed later by f.close() only closes the file if execution actually reaches that close() line; if anything between the two raises an exception, the close() call is skipped entirely and the file is left open. That's called a file handle leak — operating systems only allow a process to hold a limited number of files open at once, so a program that leaks handles repeatedly (a long-running server, a batch job that processes many files) can eventually hit that limit and start failing to open anything at all. with is built on Python's context manager protocol specifically to make this class of bug impossible: cleanup runs on every exit path, normal or exceptional, with no extra code required.
Treating with as just "shorter syntax" without knowing the actual failure mode (a leaked handle from a skipped close()) it exists to prevent, or believing manually calling close() right after the risky code is just as safe.
"If an exception is raised inside a with block, does the file still get closed before the exception propagates up?" (Yes — the file's __exit__ method runs as the block is exited for any reason, including an uncaught exception, before that exception continues propagating to whatever called this code.)
2 What's the difference between "r", "w", and "a" mode, and what's the real risk of mixing them up?
"r" (the default) opens a file for reading only and fails if the file doesn't exist. "w" opens a file for writing and erases its entire existing content the instant the file is opened — before a single new line is even written. "a" opens a file for appending, adding new content after whatever's already there, without touching the existing data. The genuinely dangerous mistake is opening a file in "w" mode when the actual intent was to add one more entry: that single line silently destroys everything that file held before, with no undo — there's no recycle bin, no confirmation prompt, nothing. This is a real production incident category: a script meant to append a log entry or a saved record that instead opens with "w" by a typo or copy-paste mistake, wiping out data that took a long time to accumulate.
Not knowing that "w" erases content immediately on open (before any .write() call), or treating "a" and "w" as interchangeable "ways to add data to a file."
"A script is supposed to add one line to an existing log file every time it runs, but someone accidentally wrote open("app.log", "w") instead of "a". What happens to the log file the second time the script runs?" (Everything the log file held after the first run is erased the instant the second run opens it in "w" mode, and only that run's one new line survives — all prior history is permanently gone.)
3 Why should you catch FileNotFoundError specifically, rather than a bare except:, around an open() call?
A bare except: catches every exception open() could possibly raise for any reason — a genuinely missing file (FileNotFoundError), a permissions problem (PermissionError), or even an unrelated bug like a TypeError from passing the wrong type as a filename — and treats all of them identically. That means a real, unexpected programming bug gets silently swallowed by error-handling logic written only for "the file might not exist," and the program limps along with a misleading fallback instead of surfacing the actual mistake with a clear traceback. Naming FileNotFoundError specifically means the program reacts correctly only to the one failure it actually anticipated (a missing file, which is entirely expected and outside the program's control), while a genuinely different problem — like a permissions issue that needs a different message, or a real bug — still surfaces normally instead of being mistaken for a missing file.
Reaching for a bare except: around file operations as a reflex "just in case," rather than naming the specific exception(s) actually expected (FileNotFoundError, and separately PermissionError if that's also anticipated).
"If a file exists but the operating system won't allow the program to read it, and the code only catches FileNotFoundError, what happens?" (The PermissionError that gets raised instead doesn't match the except FileNotFoundError clause, so it isn't caught there — it propagates up uncaught unless a separate except PermissionError clause is added to handle that distinct failure.)
4 Why does hand-splitting a CSV line on commas with .split(",") break, and what does csv.reader do differently?
.split(",") treats every single comma in the line as a field separator, with no concept that a comma can appear inside a field's actual data. A row like Widget,"Acme, Inc.",19.99 is meant to have exactly three fields, with the comma inside "Acme, Inc." protected by quotes specifically so it isn't mistaken for a separator — but .split(",") ignores those quotes entirely and produces four fields instead of three, silently corrupting the row's structure. csv.reader understands the CSV format's actual quoting rules: it tracks whether it's currently inside a quoted field and only treats a comma as a separator when it's genuinely outside any quotes, so "Acme, Inc." correctly comes back as one single field. This is exactly the kind of subtle, hard-to-notice bug that only shows up once real-world data (a company name, an address, a comment field) happens to contain a comma — which is common enough that hand-splitting CSV data is considered a real anti-pattern in production code.
Reaching for .split(",") on anything that might be genuine CSV data "because it's simpler," without recognizing that any field containing a comma will silently produce the wrong number of fields.
"Given the line Widget,\"Acme, Inc.\",19.99, how many elements does line.split(",") produce, versus how many fields csv.reader correctly produces?" (.split(",") produces 4 elements — ['Widget', '"Acme', ' Inc."', '19.99'] — while csv.reader correctly produces 3 fields: ['Widget', 'Acme, Inc.', '19.99'], treating the quoted comma as part of one field.)
5 When is csv.DictReader's extra readability actually worth it over plain csv.reader?
csv.reader gives back a plain list per row, so working with it means remembering that, say, row[0] is the product name and row[2] is the price — correct today, but silently wrong the moment a column gets added, removed, or reordered in the source file, since nothing about the code visibly documents what each index actually means. csv.DictReader uses the header row to turn every row into a dictionary, so the same access becomes row["product"] and row["price"] — self-documenting, and immune to column reordering as long as the column names stay the same. That readability and safety is worth the small extra overhead any time a CSV file has more than a couple of columns, or when the code is read/maintained by someone other than whoever wrote it. Plain csv.reader is still perfectly reasonable for a small, stable, well-understood file (or when the whole row just needs to be passed along unchanged) where naming every column by index isn't actually a readability problem in practice.
Treating DictReader as strictly "better" in every case with no tradeoff at all, or not being able to articulate the concrete risk (silent breakage on column reordering, unclear intent) that plain index-based csv.reader access carries.
"A CSV file's columns get reordered from name,price to price,name. Which approach silently breaks: code using row[0]/row[1] from csv.reader, or code using row["name"]/row["price"] from csv.DictReader?" (The csv.reader code silently breaks — row[0] now holds the price instead of the name, with no error at all, just wrong data. The DictReader code keeps working correctly, since it looks up columns by name rather than position.)
6 What's the conceptual difference between text mode and binary mode when opening a file?
Text mode (the default, used by every example in this chapter) treats a file's contents as ordinary strings, automatically handling the details of how text is encoded on disk so a program just works with str values. Binary mode ("rb" for reading, "wb" for writing) instead reads and writes raw bytes with no text interpretation at all — the right choice for files that aren't text in the first place, like images, audio files, or PDFs, where forcing a text interpretation would produce garbage or outright fail. The dividing line is simple: if a human could meaningfully open the file in a plain text editor and read it (.txt, .csv, log files, source code), text mode is correct; if the file is fundamentally a sequence of bytes with its own binary structure that isn't "text" at all, binary mode is required instead.
Believing binary mode is just "text mode but faster" or some kind of performance optimization, rather than understanding it's about what kind of data the file actually contains.
Follow-up"Would you open a .jpg image file in text mode or binary mode, and why?" (Binary mode — a .jpg file is raw image data, not text, so opening it in text mode would try to decode bytes that don't represent valid text at all, which either fails outright or produces meaningless, corrupted results.)
7 What's the difference between a relative path and an absolute path, and why can a relative path behave differently depending on where a script is run from?
A relative path like "notes.txt" has no folder information in it at all, so Python has to decide where to start looking — and it starts from the current working directory, meaning wherever the python3 command was actually launched from, not necessarily the folder the script file itself lives in. That's a common source of "it works on my machine" bugs: a script that opens "notes.txt" works fine when run from inside its own folder, but fails with FileNotFoundError the moment someone runs the exact same script from a different folder, because the relative path now resolves somewhere else entirely. An absolute path like /home/user/project/notes.txt always points to the exact same file no matter where the program was launched from, sidestepping that problem — but at the cost of hard-coding one specific location on one specific machine, which breaks the moment the project moves anywhere else. The common real-world fix isn't "always use absolute paths" but establishing a consistent, known working directory convention (like this course's practice of cd-ing into a project's own folder before running it) so relative paths behave predictably every time.
Assuming a relative path is always resolved relative to the script file's own location (it isn't — it's resolved relative to the current working directory, which depends on where the command was run from), or assuming absolute paths are simply "the safer default" with no real downside.
Follow-up"A script contains open("data.txt") and lives in /home/user/project/. If it's run as python3 /home/user/project/script.py from inside /home/user/, where does Python look for data.txt?" (In /home/user/ — the current working directory the command was run from — not in /home/user/project/ where the script file itself lives; if data.txt is actually sitting in the project/ folder, this call fails with FileNotFoundError.)
8 Why does csv.writer/csv.DictWriter require opening the output file with newline=""?
The csv module manages its own line-ending logic internally so it can produce correctly formatted CSV output on every platform consistently. If the file is opened in normal text mode without newline="", Python's own text-mode line-ending translation can interact with the csv module's line endings and produce extra blank lines between rows on some platforms (this shows up most often on Windows, where text mode by default translates \n to \r\n, which then collides with what csv.writer already writes). Passing newline="" tells Python not to do any of its own newline translation, leaving line-ending handling entirely up to the csv module, which is exactly what produces correct, clean output regardless of platform. It's a small, easy-to-forget detail, but it's specific to files opened for csv.writer/csv.DictWriter — not something needed for ordinary text file writes.
Not knowing newline="" exists at all (leading to hard-to-explain extra blank lines in CSV output on some machines but not others), or assuming it's just boilerplate with no real effect.
"If a teammate reports their exported CSV file has an extra blank line after every row, but only when they run it on Windows, what's the most likely cause?" (The file was opened for csv.writer without newline="", so Python's own text-mode newline translation on Windows is adding \r\n line endings on top of what the csv module already writes, producing the extra blank lines.)
9 If a program needs to both read a file's current content and then write new content back into it, why doesn't "r" mode or "w" mode alone work?
"r" mode only allows reading — calling .write() on a file opened this way raises an error immediately, since the file was never opened with permission to write at all. "w" mode allows writing, but it erases the file's entire existing content the instant it's opened, which destroys exactly the data a read-modify-write operation needs to read first. "r+" mode is built for exactly this situation: it opens a file for both reading and writing without erasing anything up front, so a program can read the current content, decide what the new content should be, and write it back — typically after calling file.seek(0) to move back to the start of the file, since the read operation already advanced the file's internal position to the end.
Suggesting "w" mode as a way to "read then update" a file (it can't read at all after erasing, and the erasure itself already destroys the original content before any read could happen), or forgetting that seek(0) is needed before writing after a read in "r+" mode.
"In "r+" mode, what happens if a program reads the file's content and then calls .write(...) without first calling file.seek(0)?" (The write happens starting from wherever the file's internal position currently is — the end of the file, since reading moved it there — so instead of overwriting the existing content from the start, the new text gets appended after it instead.)
10 Why is checking "does this file exist?" before opening it (LBYL) considered weaker than just opening it inside a try/except FileNotFoundError (EAFP)?
An upfront existence check and the actual open() call happen at two separate moments in time, and a file's existence isn't guaranteed to stay the same between them — another process could delete, move, or rename the file in that small gap, however unlikely that sounds in a given moment. That means an existence check passing doesn't actually guarantee the subsequent open() will succeed, so the check provides a false sense of safety while still requiring the code to handle a possible failure anyway. Just opening the file directly inside try/except FileNotFoundError sidesteps that timing gap entirely — there's no "check, then act" race condition, because the one operation that actually matters (opening the file) is the one being directly protected. This is the same EAFP philosophy from Chapter 12 (Easier to Ask Forgiveness than Permission), applied specifically to file access.
Believing an existence check followed immediately by open() is just as safe as wrapping the open() itself in try/except, without recognizing the race-condition gap between the two separate operations.
"Give a concrete (if unlikely) scenario where an existence check passes but the immediately following open() still fails." (Another process or user deletes the file in the brief moment between the existence check returning True and the open() call actually running — rare, but exactly the class of bug that wrapping open() itself in try/except FileNotFoundError avoids entirely, since it never depends on that separate, earlier check being accurate.)
11 In a real-world log-analysis script, why should reading the log file be wrapped in try/except, but the rest of the processing logic usually doesn't need to be?
Whether a log file even exists and is readable is genuinely outside a program's control — it can be deleted, not yet generated, on a different path than expected, or restricted by permissions, all for reasons that have nothing to do with a bug in the analysis script itself. That's exactly the kind of operation Chapter 12 taught belongs in a try/except: an anticipated failure mode with a real, sensible response (print a helpful message, skip this file, use a default). Once the file is successfully open and its lines are in memory as plain strings, counting log levels, searching for a keyword, or building a dictionary of error frequencies is ordinary, deterministic Python logic with no external failure mode — wrapping that in try/except too would only risk hiding a genuine bug in the processing logic behind an exception handler that was never meant to catch it. The rule of thumb: wrap the boundary where your program touches the outside world (the file system), not the internal logic that operates on data already safely in memory.
Wrapping the entire script (including pure in-memory processing logic) in one broad try/except, rather than isolating the exception handling specifically around the file-opening boundary where a real, external failure can actually occur.
"A log-analysis script wraps its entire body — file open, counting, searching, exporting — in one try/except Exception. A typo causes a NameError in the counting logic. What happens?" (The NameError — a genuine bug, unrelated to the file actually being missing — gets silently caught by the same broad handler meant for a missing log file, likely printing a misleading "file not found"-style message instead of surfacing the real typo clearly.)
12 Why does .write() not add a newline automatically the way print() does, and what's the practical consequence?
print() is designed for convenient console output, so it adds a trailing newline by default so each call's output naturally lands on its own line. file.write() is a lower-level operation that writes exactly the string it's given — nothing more, nothing less — because a file isn't always meant to hold one "line" per logical piece of data the way a terminal display is; sometimes a program genuinely wants to build up a file's content piece by piece without an automatic newline forced in after every call. The practical consequence is that forgetting "\n" in a .write() call causes the next write to land immediately after the previous one on the same line, producing a file where several logically separate entries have run together — a very common beginner bug when translating print() habits directly into .write() calls.
Assuming file.write("some text") behaves exactly like print("some text") and automatically starts a new line for the next write.
"file.write("Eggs") followed by file.write("Bread"), with no "\n" in either call — what does the file actually contain?" (One single line: EggsBread — both writes land back to back with nothing separating them, since neither call included its own newline character.)
13 What does csv.reader return for each row, and how is that different from what csv.DictReader returns?
csv.reader(file) yields one plain list of strings per row, including the header row itself as just an ordinary first list — it isn't treated as anything special unless the code explicitly separates it out. Every value comes back as a string, even ones that look numeric (a price column reads back as the string "19.99", not a float), so converting types is the caller's responsibility. csv.DictReader(file) automatically consumes the first row as column names, then yields every following row as a dict mapping those column names to that row's string values — so the header row is never yielded as a row of data itself, and each field is accessed by name (row["price"]) instead of by position (row[2]).
Believing csv.reader/csv.DictReader automatically convert numeric-looking fields to int/float (they don't — every value comes back as a plain string, and conversion is always explicit), or forgetting that DictReader consumes the header row itself rather than yielding it as ordinary data.
"Given a CSV column of prices like 19.99, what Python type does row["price"] actually hold when read with csv.DictReader?" (str — the string "19.99", not a float; converting it with float(row["price"]) is a separate, explicit step the calling code has to do itself.)
14 In a batch job that processes a new log file every night, why does a file-handle leak matter more than it would in a short one-off script?
A one-off script that leaks a single file handle by skipping with is rarely noticeable — the process ends shortly after, and the operating system reclaims every resource that process was holding the moment it exits, leaked handle included. A long-running batch job that runs repeatedly (say, once every night, for months or years) and leaks a handle on every single run behaves completely differently: each run's leaked handle adds to whatever the process is already holding from every previous run, since the process itself never restarts to clear them out. Given enough nights, that slow accumulation eventually hits the operating system's limit on how many files a single process can have open at once, and the job starts failing to open anything at all — a failure that can take weeks to surface and is genuinely confusing to diagnose after the fact, since the code "works" for a long time before it doesn't. with makes this entire failure mode impossible by guaranteeing every file is closed at the end of its block, run after run, with nothing to slowly accumulate.
Treating "just use with" as a stylistic nicety rather than being able to explain the concrete, slow-building failure (hitting the OS's open-file limit after enough repeated runs) that skipping it actually risks in a long-running or repeatedly-run program.
"A nightly batch job leaks one file handle per run because it never calls .close() and an exception always skips past it. Does this cause an immediate crash, or a problem that appears only after many runs?" (Only after many runs — each night's leaked handle adds to the ones from previous nights, and the job keeps working fine for a long stretch until the accumulated total finally hits the operating system's per-process limit on open files, at which point it starts failing to open anything.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.