File Handling
File Handling Interview with follow-up questions
1. What are the different modes in which a file can be opened in Python?
open() takes a mode string that combines an access character with optional modifiers:
'r'— read (the default); errors if the file doesn't exist.'w'— write; truncates an existing file to empty, or creates a new one.'a'— append; writes to the end, creating the file if needed (never truncates).'x'— exclusive creation; creates a new file but fails if it already exists (good for avoiding accidental overwrites).
Modifiers combine with the above:
't'— text mode (default): reads/writesstr, handles encoding and newline translation.'b'— binary mode: reads/writesbytes, no decoding — use for images, archives, etc.'+'— open for both reading and writing (e.g.'r+','w+').
What interviewers expect you to add:
- Always use a
withblock so the file is closed even on error, and always specifyencodingin text mode — the default is platform-dependent and a frequent source of bugs:
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
- Text vs binary is the distinction that trips people up: text yields
strand decodes; binary yieldsbytes. Mixing them raisesTypeError. - Prefer
pathlib.Path(Path("data.txt").read_text(encoding="utf-8")) for concise reads/writes in modern code.
Follow-up 1
What does the 'r+' mode mean?
The 'r+' mode in Python opens a file for both reading and writing. It allows you to read from and write to the file. If the file does not exist, an error is raised.
Follow-up 2
What is the difference between 'w' and 'a' modes?
The 'w' mode in Python opens a file for writing. If the file already exists, it truncates the file to zero length. If the file does not exist, it creates a new file.
The 'a' mode in Python opens a file for appending. It allows you to add data to the end of the file. If the file does not exist, it creates a new file.
Follow-up 3
What happens if a file that does not exist is opened in 'r' mode?
If a file that does not exist is opened in 'r' mode in Python, a FileNotFoundError is raised.
Follow-up 4
Can you write and read a file simultaneously?
Yes, you can write and read a file simultaneously in Python. To do this, you can open the file in 'r+' mode. This allows you to read from and write to the file at the same time. However, it is important to be careful with the file pointer position when switching between reading and writing operations.
2. How do you read an entire file in Python?
To read an entire file, open it in a with block and call read(), which returns the whole content as a single string:
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
The with statement guarantees the file is closed even if an error occurs, and specifying encoding="utf-8" avoids platform-dependent decoding bugs.
What interviewers want you to weigh in on:
read()loads the whole file into memory — fine for small files, dangerous for large ones. For big files, iterate line by line instead, which streams and stays memory-cheap:
with open("big.log", encoding="utf-8") as f:
for line in f: # lazy, one line at a time
process(line)
readlines()returns alist[str]of all lines (also loads everything);readline()reads one line at a time.- Modern shortcut:
pathlib.Path("file.txt").read_text(encoding="utf-8")does the open/read/close in one line. - Binary files use mode
"rb"and returnbytes— noencoding. The key follow-up is always "what if the file is huge?" — the answer is: don'tread()it all; stream it.
Follow-up 1
What is the difference between read() and readlines()?
The read() method reads the entire content of a file as a single string, while the readlines() method reads the content of a file line by line and returns a list of strings, where each string represents a line of the file.
Here is an example that demonstrates the difference:
with open('file.txt', 'r') as file:
content = file.read()
print(content)
with open('file.txt', 'r') as file:
lines = file.readlines()
print(lines)
In this example, the first print() statement will output the entire content of the file as a single string, while the second print() statement will output a list of strings, where each string represents a line of the file.
Follow-up 2
How would you read a file line by line in Python?
To read a file line by line in Python, you can use a for loop to iterate over the file object. Here is an example:
with open('file.txt', 'r') as file:
for line in file:
print(line)
In this example, the open() function is used to open the file in read mode, and then the file object is iterated over using a for loop. Each iteration of the loop will assign the current line of the file to the variable line, which can then be processed or printed.
Follow-up 3
What happens if you try to read a file that is not open?
If you try to read a file that is not open, you will encounter a ValueError with the message 'I/O operation on closed file'. This error occurs because the file object used for reading the file has already been closed or was never opened in the first place.
Here is an example that demonstrates the error:
file = open('file.txt', 'r')
file.close()
content = file.read()
In this example, the open() function is used to open the file in read mode, but then the close() method is called on the file object. After the file is closed, attempting to call the read() method on the closed file object will raise a ValueError.
Follow-up 4
How can you handle large files that do not fit into memory?
To handle large files that do not fit into memory, you can read the file in chunks instead of reading the entire file at once. This can be done by specifying a chunk size when reading the file.
Here is an example that demonstrates reading a large file in chunks:
chunk_size = 1024
with open('large_file.txt', 'r') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
# Process the chunk
print(chunk)
In this example, a chunk_size of 1024 bytes is specified. The file is read in chunks of this size using a while loop. The loop continues until there are no more chunks to read. Each chunk can then be processed or stored as needed.
3. How do you write to a file in Python?
To write to a file, open it in a write mode and call write() (for a string) or writelines() (for an iterable of strings). Always use a with block so the file is flushed and closed even if an error occurs:
with open("example.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.writelines(line + "\n" for line in ["a", "b", "c"])
What interviewers expect you to get right:
withover manualclose(). The oldf = open(...); f.write(...); f.close()leaks the handle if anything between raises.withguarantees cleanup — the modern, exception-safe way.- Mode choice matters:
"w"truncates any existing content,"a"appends, and"x"creates only if the file doesn't already exist (so you don't clobber data). - Specify
encoding="utf-8"— the default is platform-dependent and a classic portability bug. write()doesn't add newlines — you include\nyourself. It also returns the number of characters written.- Binary uses mode
"wb"and writesbytes, notstr. - Modern shortcut:
pathlib.Path("example.txt").write_text("Hello", encoding="utf-8")does open/write/close in one call.
Follow-up 1
What happens if you try to write to a file that is opened in read mode?
If you try to write to a file that is opened in read mode, you will get a PermissionError with the message 'Permission denied'. This is because opening a file in read mode only allows you to read the contents of the file, not modify or write to it. To write to a file, you need to open it in write mode.
Follow-up 2
How would you write a list of strings to a file?
To write a list of strings to a file, you can use a loop to iterate over the list and write each string to the file. Here's an example:
# Open the file in write mode
file = open('example.txt', 'w')
# List of strings
strings = ['Hello', 'World', 'Python']
# Write each string to the file
for string in strings:
file.write(string + '\n')
# Close the file
file.close()
Follow-up 3
How can you append to an existing file?
To append to an existing file, you can open the file in append mode using the open() function with the mode parameter set to 'a'. Then, you can use the write() method to write data to the file. The data will be added to the end of the file without overwriting the existing content. Here's an example:
# Open the file in append mode
file = open('example.txt', 'a')
# Write data to the file
file.write('Appended data')
# Close the file
file.close()
Follow-up 4
What is the use of the flush() method?
The flush() method is used to flush the internal buffer of a file object. When you write data to a file, it is first stored in an internal buffer instead of being immediately written to the file. The flush() method forces the data in the buffer to be written to the file immediately. This can be useful in situations where you want to ensure that all the data is written to the file before performing other operations. Here's an example:
# Open the file in write mode
file = open('example.txt', 'w')
# Write data to the file
file.write('Hello, World!')
# Flush the buffer
file.flush()
# Close the file
file.close()
4. How do you handle exceptions during file operations in Python?
Wrap file operations in try/except to catch I/O failures, and let a context manager handle cleanup so you don't need a manual finally. The modern, correct pattern:
try:
with open("filename.txt", "r", encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
print("File does not exist")
except PermissionError:
print("No permission to read the file")
except OSError as exc: # broad I/O fallback (disk full, etc.)
print(f"I/O error: {exc}")
Why this beats the old try/finally: file.close() approach — and what interviewers probe:
- The
withblock closes the file automatically, even on error, so a separatefinally: f.close()is redundant. The old style also crashes infinallyifopen()itself failed andfilewas never assigned (NameError) — a real gotcha. - Catch specific exceptions.
FileNotFoundError,PermissionError, andIsADirectoryErrorare all subclasses ofOSError(the modern name;IOErroris just an alias). Handle the precise cases you can recover from, then fall back toOSError. - Use
UnicodeDecodeErrorfor encoding mismatches when reading text — distinct from I/O errors. - For "ignore if missing,"
contextlib.suppress(FileNotFoundError)is cleaner than an emptyexcept.
Follow-up 1
What is the role of the finally block in exception handling?
The finally block in exception handling is used to define a block of code that will be executed regardless of whether an exception occurs or not. It is typically used to perform cleanup operations, such as closing files or releasing resources, that need to be done regardless of the outcome of the try block. The finally block is executed after the try block and any associated except blocks, even if an exception is raised or caught. Here's an example:
try:
# perform some operations
except SomeException:
# handle the exception
finally:
# cleanup operations
Follow-up 2
What kind of exceptions can occur during file operations?
Several exceptions can occur during file operations in Python. Some common exceptions include:
- IOError: Raised when an I/O operation fails, such as when a file cannot be opened or read.
- FileNotFoundError: Raised when a file or directory is requested but cannot be found.
- PermissionError: Raised when a file operation is not permitted, such as when trying to write to a read-only file.
- IsADirectoryError: Raised when a directory is specified where a file is expected.
- NotADirectoryError: Raised when a file is specified where a directory is expected.
These are just a few examples, and there are other exceptions that can occur depending on the specific file operation and the state of the system.
Follow-up 3
How can you ensure that a file is closed after an exception occurs?
To ensure that a file is closed after an exception occurs, you can use a try-finally block. Inside the try block, you can open the file and perform the necessary operations. Then, in the finally block, you can close the file. This way, even if an exception occurs, the file will still be closed. Here's an example:
file = None
try:
file = open('filename.txt', 'r')
# perform file operations
finally:
if file:
file.close()
Follow-up 4
What is the use of the with statement in file operations?
The with statement in file operations is used to automatically handle the opening and closing of files. It ensures that the file is properly closed, even if an exception occurs. The with statement creates a context manager, which is an object that defines the methods __enter__ and __exit__. When the with statement is executed, it calls the __enter__ method of the context manager, which opens the file and returns it. Then, the code inside the with block is executed. Finally, the __exit__ method is called, which closes the file. Here's an example:
with open('filename.txt', 'r') as file:
# perform file operations
5. How do you work with CSV files in Python?
Use the built-in csv module, which handles the tricky parts of CSV — quoting, embedded commas, and newlines inside fields — that naive str.split(",") gets wrong.
Reading with csv.reader (rows as lists), or DictReader to key by header:
import csv
with open("data.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], row["age"])
Writing with csv.writer / DictWriter:
with open("out.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerow({"name": "Ada", "age": 36})
What interviewers expect you to know:
- Always pass
newline=""toopen(). Omitting it causes blank lines / mangled rows on some platforms because the csv module does its own newline handling — the single most common CSV bug. DictReader/DictWriterare usually cleaner than positional rows since columns are named.- Specify
delimiter/quotecharfor TSV or non-standard files (delimiter="\t"), or use a registered dialect. - Everything reads as strings — convert types (
int(row["age"])) yourself. - For large or analytical workloads,
pandas(read_csv/to_csv) orpolarsis the practical real-world choice, but the stdlibcsvmodule is the dependency-free baseline.
Follow-up 1
What is the role of the csv module in Python?
The csv module in Python provides functionality for working with CSV (Comma Separated Values) files. It allows you to easily read from and write to CSV files using Python. The csv module provides a reader object for reading data from a CSV file, and a writer object for writing data to a CSV file. It also provides various options for customizing the behavior of the CSV reader and writer, such as specifying the delimiter character, quote character, and other options.
Follow-up 2
How do you read a CSV file using the csv module?
To read a CSV file using the csv module in Python, you can use the reader object provided by the module. Here is an example:
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Follow-up 3
How do you write to a CSV file using the csv module?
To write to a CSV file using the csv module in Python, you can use the writer object provided by the module. Here is an example:
import csv
data = [
['Name', 'Age', 'Country'],
['John', '25', 'USA'],
['Alice', '30', 'Canada'],
['Bob', '35', 'UK']
]
with open('data.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(data)
Follow-up 4
How can you handle CSV files with a different delimiter?
By default, the csv module in Python assumes that CSV files use a comma (',') as the delimiter. However, you can handle CSV files with a different delimiter by specifying the delimiter character when working with the csv module. Here is an example:
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file, delimiter=';')
for row in reader:
print(row)
Live mock interview
Mock interview: File Handling
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.