Bird
0
0

Find the error in this code that tries to write lines to a file efficiently:

medium📝 Debug Q14 of 15
Python - File Reading and Writing Strategies

Find the error in this code that tries to write lines to a file efficiently:

lines = ['line1\n', 'line2\n', 'line3\n']
file = open('output.txt', 'w')
for line in lines:
    file.write(line)
file.close()
AUsing <code>with open()</code> is better to ensure file closes
BThe file should be opened in read mode 'r'
CThe loop should use <code>readlines()</code> instead of <code>lines</code>
DThe file is not closed properly
Step-by-Step Solution
Solution:
  1. Step 1: Check file handling safety

    Opening file without with risks leaving it open if error occurs before close().
  2. Step 2: Use with open() for automatic closing

    Replacing with with open('output.txt', 'w') as file: ensures file closes safely.
  3. Final Answer:

    Using with open() is better to ensure file closes -> Option A
  4. Quick Check:

    Use with open() to auto-close files [OK]
Quick Trick: Always use with open() to avoid forgetting file.close() [OK]
Common Mistakes:
  • Forgetting to close file on exceptions
  • Opening file in wrong mode
  • Misunderstanding readlines() vs list variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes