Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q5 of Q15
Python - Context Managers
What will be the output of this code?
try:
    with open('file.txt', 'r') as f1, open('file2.txt', 'r') as f2:
        data1 = f1.read()
        data2 = f2.read()
except FileNotFoundError:
    print('File missing')
else:
    print('Files read successfully')
ANo output
BFiles read successfully
CSyntaxError
DFile missing
Step-by-Step Solution
Solution:
  1. Step 1: Understand exception handling with multiple files

    If either file is missing, FileNotFoundError is raised and caught.
  2. Step 2: Predict output if files don't exist

    Since files likely don't exist, the except block prints 'File missing'.
  3. Final Answer:

    File missing -> Option D
  4. Quick Check:

    Missing file triggers except block = A [OK]
Quick Trick: Missing file triggers FileNotFoundError catch [OK]
Common Mistakes:
MISTAKES
  • Assuming files always exist
  • Expecting else block to run on error
  • Confusing syntax error with runtime error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes