Computer Science

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

Python Data Handling

2 Likes

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.

Answered By

2 Likes


Related Questions