Bird
0
0

You want to safely read a file named log.txt and automatically close it after reading. Which code snippet correctly does this using Python's best practice?

hard📝 Application Q15 of 15
Python - File Handling Fundamentals
You want to safely read a file named log.txt and automatically close it after reading. Which code snippet correctly does this using Python's best practice?
Afile = open('log.txt', 'r') content = file.read() file.close()
Bopen('log.txt', 'r').read()
Cfile = open('log.txt', 'r') content = file.read()
Dwith open('log.txt', 'r') as file: content = file.read()
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe file handling

    Using with statement ensures the file is automatically closed after the block finishes, even if errors occur.
  2. Step 2: Compare options

    file = open('log.txt', 'r') content = file.read() file.close() requires manual close, C misses close, D reads but does not save content or close explicitly.
  3. Final Answer:

    with open('log.txt', 'r') as file: content = file.read() -> Option D
  4. Quick Check:

    Use with statement for auto-close [OK]
Quick Trick: Use with open(...) as file for automatic closing [OK]
Common Mistakes:
  • Forgetting to close file manually
  • Not using with statement for safety
  • Ignoring file object after open()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes