CBSE Class 12 Computer Science Question 42 of 136

Data File Handling — Question 7

Back to all questions
7
Question

Question 7

What will be the output of the following snippet?

f = None
for i in range(5):
    with open("data.txt", "w") as f:
       if i > 2:
        break
print(f.closed)
  1. True
  2. False
  3. None
  4. Error
Answer

True

Reason — Initially, the variable f is assigned None. The code then enters a for loop that runs five times (for i in range(5)). Inside the loop, a file named "data.txt" is opened in write mode ("w") using the with statement. If the value of i is greater than 2, the loop breaks using break. After the loop breaks, the print(f.closed) statement is executed outside the with block. Since the file object f was opened within the with block, it is automatically closed when the block exits. The f.closed attribute returns True if the file is closed, which happens because of the with statement's automatic closing behavior.