Bird
0
0

Identify the problem in this code:

medium📝 Debug Q7 of 15
Python - Context Managers
Identify the problem in this code:
with open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2:
    data = f1.read()
f2.write(data)
Af2.write(data) is outside the with block, so f2 is closed
Bf1.read() cannot be used with multiple files
CMissing exception handling for file operations
Df2.write() requires a string, data might be bytes
Step-by-Step Solution
Solution:
  1. Step 1: Check indentation of f2.write(data)

    It is outside the with block, so f2 is closed when this line runs.
  2. Step 2: Understand consequence

    Writing to a closed file causes a ValueError or IOError.
  3. Final Answer:

    f2.write(data) is outside the with block, so f2 is closed -> Option A
  4. Quick Check:

    Writing after with block closes file = C [OK]
Quick Trick: Keep file operations inside with block [OK]
Common Mistakes:
  • Ignoring indentation importance
  • Assuming read can't be used with multiple files
  • Thinking exception handling is mandatory here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes