Python File Handling Interview Questions
Last updated 2026-11-19
File handling questions are popular in practical Python tests because they are easy to ask and easy to get subtly wrong. Interviewers check that you close files reliably, understand open modes, choose the right read method for the file size, and handle text encodings and common formats such as CSV and JSON.
The answers below cover the built-in open function, the with statement, pathlib, the csv and json modules, and the small details that cause bugs: newline handling, truncation by the w mode, and the position of the file pointer.
| Level | Fresher to 2 years |
|---|---|
| Focus | open, with, text and binary modes, csv, json, pathlib |
| Version | Python 3.9 and later |
Mode cheat sheet
Modes combine one of r, w, a, x with an optional b for binary or t for text, and an optional plus for read and write.
- r: read, file must exist (default)
- w: write, creates the file or truncates it to zero length
- a: append, writes always go to the end
- x: create exclusively, fails if the file exists
- r+: read and write without truncating
Related topics
Errors raised while opening files are covered in exception handling questions, and lazy reading of big files in generators and iterators. Overall preparation is in how to crack a Python interview.
Python File Handling Interview Questions: questions with worked answers
1 Why should you use the with statement to open files?
easywith guarantees the file is closed when the block ends, even if an exception occurs, because the file object is a context manager whose __exit__ calls close. Without it you must call close in a finally block yourself. Unclosed files can lose buffered writes and leak file descriptors, which matters in long-running programs.
pythonwith open("notes.txt", "w", encoding="utf-8") as f: f.write("hello\n") print(f.closed) # True2 What happens if you open an existing file in w mode?
easyThe file is truncated to zero length as soon as open succeeds, before you write anything, so the old contents are lost. Use a to add to the end, r+ to modify in place, or x to fail if the file already exists. This is a frequent source of accidental data loss.
3 What is the difference between read, readline and readlines?
mediumread() returns the whole remaining content as one string, or n characters if given a size. readline() returns one line including its newline, and an empty string at end of file. readlines() returns a list of all lines. For large files, loop over the file object itself, which streams one line at a time with constant memory.
pythonwith open("data.txt", "w") as f: f.write("a\nb\nc\n") with open("data.txt") as f: print(f.readline()) # a (plus newline) print(f.readlines()) # ['b\n', 'c\n']4 Predict the output: how does the file pointer move?
mediumA file has a current position. Reading or writing advances it, tell() reports it and seek(offset, whence) moves it. After read() consumes everything, a second read() returns an empty string until you seek back to 0.
pythonwith open("p.txt", "w+") as f: f.write("abcdef") f.seek(0) print(f.read(2), f.tell()) # ab 2 print(f.read()) # cdef print(repr(f.read())) # '' f.seek(0) print(f.read(1)) # a5 What is the difference between text mode and binary mode?
mediumText mode decodes bytes into str using an encoding and translates newlines, so on Windows the line ending is converted to a plain newline on read. Binary mode, with b, returns raw bytes with no decoding or translation, needed for images, archives and any non-text data. Always give encoding explicitly in text mode, since the default depends on the platform and locale.
6 How do you count the lines or words in a large file efficiently?
mediumIterate over the file and count as you go, never read everything at once. For words, split each line. The memory use is the size of one line, so a multi-gigabyte file is fine. Use a generator expression with sum for a compact version.
pythonwith open("data.txt", encoding="utf-8") as f: lines = sum(1 for _ in f) with open("data.txt", encoding="utf-8") as f: words = sum(len(line.split()) for line in f) print(lines, words) # 3 37 How do you read and write CSV files correctly?
mediumUse the csv module, which handles quoting, embedded commas and delimiters. Open the file with newline='' so the module controls line endings. csv.DictReader maps each row to a dictionary keyed by the header, and DictWriter does the reverse. Values are always strings, so convert numbers yourself.
pythonimport csv with open("p.csv", "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=["name", "score"]) w.writeheader() w.writerow({"name": "Asha, K", "score": 90}) with open("p.csv", newline="", encoding="utf-8") as f: print(list(csv.DictReader(f))) # [{'name': 'Asha, K', 'score': '90'}]8 How do you work with JSON files?
mediumjson.load reads from a file object and json.dump writes to one, while loads and dumps work on strings. JSON supports dict, list, str, int, float, bool and None, so tuples come back as lists and dictionary keys become strings. Custom objects need a default function or must be converted first.
pythonimport json data = {"id": 1, "tags": ("a", "b"), 2: "x"} s = json.dumps(data) print(s) # {"id": 1, "tags": ["a", "b"], "2": "x"} print(json.loads(s)["tags"]) # ['a', 'b']9 Why prefer pathlib over os.path?
mediumpathlib.Path represents paths as objects, uses the / operator to join parts, works across operating systems, and offers read_text, write_text, exists, glob, mkdir and iterdir directly. The code is shorter and avoids manual string joins. Path.read_text loads a whole file, so it suits small files.
pythonfrom pathlib import Path p = Path("out") / "notes.txt" p.parent.mkdir(exist_ok=True) p.write_text("hi", encoding="utf-8") print(p.suffix, p.stem, p.exists()) # .txt notes True10 How would you copy a file or process a file without risking a half-written result?
hardWrite to a temporary file in the same directory, flush and close it, then replace the target with os.replace, which is atomic on the same filesystem. Readers either see the old file or the complete new one. For copying, shutil.copyfile streams in chunks. For appending logs, open with a and let the operating system append atomically per write.
11 What is buffering, and what do flush and fsync do?
mediumWrites go first into a buffer in memory, and are sent to the operating system when the buffer fills, on flush, or on close. flush pushes the buffer to the operating system, but the data may still be in the kernel cache. os.fsync(f.fileno()) asks the operating system to write it to disk. Most programs only need close or with; fsync matters for durability, such as database-like writes.
12 How do you read a file in chunks, for example for hashing or copying?
mediumUse two-argument iter with a sentinel, or a loop that reads a fixed size until an empty result. Chunking keeps memory constant and works for binary files of any size.
pythonimport hashlib h = hashlib.sha256() with open("p.csv", "rb") as f: for chunk in iter(lambda: f.read(8192), b""): h.update(chunk) print(len(h.hexdigest())) # 6413 What does the exception FileNotFoundError tell you, and how do you handle missing files?
easyIt is a subclass of OSError raised when open targets a path that does not exist, for example in r mode. Catch it specifically and decide what to do: create defaults, warn the user, or exit. Other related errors are PermissionError and IsADirectoryError. Prefer try and except over checking exists first, because the file can disappear between the check and the open.
pythontry: with open("missing.txt") as f: data = f.read() except FileNotFoundError: data = "" print(repr(data)) # ''
Frequently asked questions
Do I need to call close if I use with?
No. The with block closes the file for you, even when an exception interrupts it.
What encoding should I use?
UTF-8 is the safe default for new text files. Pass encoding='utf-8' explicitly, because the default encoding of open depends on the operating system.
How do I append to a file without erasing it?
Open it with mode a. Each write goes to the end regardless of the pointer position.
How do I read a file backwards?
For a small file, read the lines and reverse the list. For a huge file, use seek from the end in binary mode and read blocks backwards.
Related guides
More in Programming Language Interview Questions by Language
- Python Generators and Iterators Interview Questions
- Python Interview Questions and Answers
- Python Lambda, Map, Filter and Reduce Interview Questions
- Python List, Dict and Set Interview Questions
- Python Memory Management Interview Questions
- Python Multithreading and Multiprocessing Interview Questions
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions
- SQL Indexes Interview Questions
- SQL Interview Questions and Answers