Bird
Raised Fist0

How can you read the entire content of a file and safely handle the case when the file might not exist, printing "File missing" if so?

hard🚀 Application Q9 of Q15
Python - File Reading and Writing Strategies
How can you read the entire content of a file and safely handle the case when the file might not exist, printing "File missing" if so?
Atry: file = open('data.txt', 'w') content = file.read() except IOError: print('File missing')
Btry: with open('data.txt', 'r') as f: content = f.read() except FileNotFoundError: print('File missing')
Cif os.path.exists('data.txt'): with open('data.txt', 'r') as f: content = f.read() else: print('File missing')
Dwith open('data.txt', 'r') as f: content = f.read() if not content: print('File missing')
Step-by-Step Solution
Solution:
  1. Step 1: Use try-except to catch missing file

    Opening file in try block catches FileNotFoundError if file is missing.
  2. Step 2: Read content if file exists, else print message

    In except block, print 'File missing' to handle error gracefully.
  3. Final Answer:

    try: with open('data.txt', 'r') as f: content = f.read() except FileNotFoundError: print('File missing') -> Option B
  4. Quick Check:

    Use try-except FileNotFoundError for safe file read [OK]
Quick Trick: Use try-except FileNotFoundError to handle missing files [OK]
Common Mistakes:
MISTAKES
  • Checking content instead of file existence
  • Opening file in write mode by mistake
  • Not catching correct exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes