CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy
A developer is writing a Python script to automate file processing. The script needs to iterate through a list of filenames, open each file, read its content, and then close it. Which Python construct is best suited for ensuring that a file is always properly closed, even if errors occur during content processing?
- ACalling `file.close()` immediately after `file.read()`.
- BUsing a `with` statement for file handling.
- CAssigning the file object to a global variable.
- DUsing a `try-except` block around `open()` and `close()` calls.
Show answer & explanationAnswer & explanation
Correct answer: B. Using a `with` statement for file handling.
The `with` statement in Python is designed for resource management, particularly for objects that need to be properly set up and torn down (like files). It ensures that the file's `__exit__` method is called automatically when the block is exited, guaranteeing that the file is closed even if an exception occurs.
Why the other options are wrong
- A. This does not guarantee closure if an error occurs between `read()` and `close()`.
- C. Assigning to a global variable does not help with ensuring proper file closure.
- D. While `try-except-finally` can close files, `with` is more idiomatic and concise for this specific purpose.
Python `with` Statement
The `with` statement in Python is used to wrap the execution of a block with methods defined by a context manager. It ensures that 'clean-up' code is executed, even if exceptions occur.
- Guarantees resource release (e.g., file closure, lock release).
- Works with objects that implement the context manager protocol (`__enter__` and `__exit__`).
- Commonly used for file I/O, database connections, and threading locks.
Memory trick: With every resource, ensure a clean exit.