Python File Handling
Common interview questions on this topic — practice explaining concepts out loud.
Here is an Interview Prep Q& module based on a Python File Handling and Exception Handling concepts covered into your materials.
Intermediate Python Interview Prep Q&A: File & Exception Handling
- Question: Why is
pathlibmodule currently preferred over older modules likeosof file system manipulation. How does basically it handle cross-platform compatibility? -
Answer:
pathlibis actually preferred because it offers a modern, object-oriented approach to file systems. Instead of treating a file path like a simple "dumb" string of text (as was common usingosmodule),pathlibtreats paths as intelligent objects; it inherently provides classes representing filesystem paths with the appropriate semantics for different operating systems, while this means it automatically adjusts path rules for cross-platform compatibility (like Windows versus Linux) without requiring developers to write separate, manual code logic for each environment. -
Question: Explain a complete four-step exception handling architecture in Python. Specifically, why is it considered a bad practice to put too much code in the
tryblock, and how does theelseclause fix this? - Answer: A complete professional architecture uses
try,except,elseandfinally. try: Tests a "dangerous" code where the error is expected to possibly occur.except: Handles specific errors if they're raised.else: Executes only if thetryblock completes successfully without any exceptions.finally: Always executes regardless of success or failure, making it perfect for resource cleanup.
Stuffing too much code into a try block is a common mistake because an except block might catch an exception from completely different line of code than intended accidentally hiding a brand-new bug, and the else clause fix this by allowing developers to separate their "dangerous" logic (put into try) from their "safe" success logic (put in else).
- Question: You are doing code review and see developer open the file using
pathlib'sp.open()method in-place without assigning it or closing it. What's a danger here. How would you fix it to ensure system stability? - Answer: The danger is the memory leak. When a file or database connection is opened it consumes an operating system resource. If it's opened in-place and not properly closed the file remains open indefinitely. Over time these unclosed resources leak memory and can eventually crash the entire server.
p.open()returns standard file object, and its closure can be verified by checking itsclosedattribute. To fix it the code should explicitly close the resource, ideally by placing the cleanup logic inside afinallyblock to guarantee the file is closed whether operation succeeds fails or panics. ```python from pathlib import Path
p = Path('data.txt') file_obj = None try: file_obj = p.open('r') # Dangerous read operations here except Exception as e: print(f"Error reading file: {e}") finally: if file_obj and not file_obj.closed: file_obj.close() print("File safely closed.") ```
- Question: Imagine you're pretty much building a secure banking application processing user withdrawals. How would actually you handle user trying to withdraw more money than they have, versus a developer mistakenly passing a negative amount into a withdrawal function?
- Answer: These two scenarios require completely different error-handling strategies:
- User Error (Business Logic): You should create a Custom Exception (e.g.,
InsufficientFundsError). Using standard built-in errors likeValueErroris too vague because it doesn't specify if user typed a letter or if their balance was empty; custom exceptions make the code self-documenting so other developers know exactly what business logic failed. -
Developer Error: You should use the
assertkeyword; assertions are debugging tools meant to actively crash the program during development if a condition is false. You would useassert withdrawal_amount > 0to catch a developer mistake instantly, rather than trying to handle it gracefully. -
Question: Is it a good practice for use the
try...exceptblock to control the normal flow of your program such as checking if a file exists before reading it; why or why not? - Answer: No, it's not a good practice, while while exceptions are incredibly powerful towards safety, they are basically computationally slow for system to process. Exceptions should probably never be used to control a normal, day-to-day flow of the program; instead of using a
tryblock just to check if a file exists you should use standard flow control, such as anif...elsestatement utilizingpathlib's.is_file()or.exists()methods; exceptions should be strictly saved for truly exceptional or unexpected events like a network dropping out unexpectedly.
Learn Together
Share a learning session in real-time with a classmate.
Share this 6-digit key with your classmate to start learning together:
Room Details
Share this 6-digit room key with others so they can join you in real-time:
Instructions: Open any course page, click "Learn Together", and click "Join Room" to enter the code.