Courseiva
Exceptions and File I/O →mediumMultiple Choice

PCAP Exceptions and File I/O Practice Question

A developer wants to ensure that a file is always closed after writing, even if an exception occurs. Which approach is considered best practice in Python?

⚠ Common exam trap

Python Institute often tests the misconception that `try/finally` with explicit `close()` is equivalent to the `with` statement, but the trap is that the `with` statement is the explicitly recommended best practice in the Python documentation and PEP 343, making it the correct answer over more manual approaches.

Answer choices

Why each option matters

Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.

Correct answer & explanation

✓

Use the with statement: with open('file.txt', 'w') as f: ...

The `with` statement in Python implements a context manager that automatically calls the file's `__exit__` method, which closes the file even if an exception occurs inside the block. This is the idiomatic and recommended approach for resource management, as it guarantees cleanup without requiring explicit `close()` calls.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • ✗

    Use try/finally with explicit f.close()

    Why it's wrong here

    Using try/finally with an explicit f.close() does guarantee that close() is called if an exception occurs, but it still requires you to manually create the file object and handle the edge case where open() itself fails, leaving f undefined. This approach becomes verbose and error-prone, especially when managing multiple resources, because you must nest or coordinate multiple finally blocks and carefully track variable scopes. It is functionally correct in simple cases, but it lacks the declarative clarity and automatic resource acquisition that Python's with statement provides.

  • ✗

    Rely on the garbage collector to close the file

    Why it's wrong here

    Relying on the garbage collector to close the file is fundamentally unreliable because CPython's reference counting tears down objects promptly, but other Python implementations (PyPy, Jython) use non-deterministic garbage-collection cycles, and even in CPython there is no language guarantee about exactly when a file object will be finalized. If the file is still buffered when the GC eventually runs without an explicit close or flush, buffered writes may be lost or not visible to other processes. This approach makes cleanup timing unpredictable and is never a safe substitute for deterministic, explicit resource management.

  • ✗

    Use try/except/finally with f.close() in both except and finally

    Why it's wrong here

    Using try/except/finally with f.close() in both the except and finally blocks is redundant and indicates a misunderstanding of how finally works: the finally block executes whether or not an exception is raised, so placing close() in the except block is unnecessary and duplicates error-prone cleanup code that must be kept in sync. Worse, if the exception originates during open() itself, f may not exist, and an unguarded f.close() inside except could raise a NameError, masking the original exception. It also clutter the logic without adding any safety, making the code harder to read and maintain.

  • ✓

    Use the with statement: with open('file.txt', 'w') as f: ...

    Why this is correct

    Using the with statement is the idiomatic Pythonic solution because it leverages the context manager protocol: open() returns a file object whose __enter__ and __exit__ methods are invoked by with, guaranteeing that __exit__ calls close() even if the body raises an exception or encounters a return/break/continue. This automatically flushes buffered writes and releases the OS file descriptor deterministically at the end of the block. It also handles the case where open() itself fails by never entering the block, so no file object needs cleanup, and it expresses the intent of scoped resource management clearly.

About these practice questions

One of 421 original PCAP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

JA

Written by Johnson Ajibi, MSc IT Security

Senior Network & Security Engineer · founder of Courseiva

This PCAP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCAP exam.