PCEP Computer Programming and Python Fundamentals Practice Question
A Python script uses the following code to open a file: f = open('data.txt', 'w'). The programmer then writes multiple lines to the file. After writing, which of the following is the BEST practice to ensure data integrity?
⚠ Common exam trap
Python Institute often tests the misconception that Python automatically closes files or that calling `close()` or `flush()` individually is sufficient, when in fact the `with` statement is the only guaranteed way to ensure proper cleanup and data integrity.
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 a with statement to open the file.
Using a `with` statement ensures that the file is automatically closed when the block exits, even if an exception occurs. This guarantees that all buffered data is flushed to disk, preventing data loss or corruption. It is the recommended best practice in Python for reliable file handling.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Call f.close() after writing.
Why it's wrong here
Works but not exception-safe.
- ✗
Call f.flush() after writing.
Why it's wrong here
Flushes buffer but does not close file.
- ✗
No action needed; Python automatically closes files.
Why it's wrong here
Not guaranteed; depends on garbage collection.
- ✓
Use a with statement to open the file.
Why this is correct
Ensures proper closing even on exceptions.
Go deeper
Related to this question
About these practice questions
This PCEP question is part of Courseiva's 498-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCEP 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 PCEP exam.