Bird
Raised Fist0

What will happen if you try to read a file that does not exist using open('nofile.txt', 'r')?

medium📝 Predict Output Q5 of Q15
Python - File Handling Fundamentals
What will happen if you try to read a file that does not exist using open('nofile.txt', 'r')?
AIt creates a new empty file
BIt raises a FileNotFoundError
CIt returns an empty string
DIt writes default content to the file
Step-by-Step Solution
Solution:
  1. Step 1: Understand 'r' mode behavior

    Opening a file in 'r' mode requires the file to exist; otherwise, an error occurs.
  2. Step 2: Identify the error raised

    If the file does not exist, Python raises a FileNotFoundError exception.
  3. Final Answer:

    It raises a FileNotFoundError -> Option B
  4. Quick Check:

    Reading non-existent file = FileNotFoundError [OK]
Quick Trick: Read mode needs existing file, else error [OK]
Common Mistakes:
MISTAKES
  • Thinking it creates a new file
  • Expecting empty string return
  • Assuming it writes default content

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes