Bird
0
0

Identify the error in this code snippet that tries to read a file line by line:

medium📝 Debug Q14 of 15
Python - File Handling Fundamentals
Identify the error in this code snippet that tries to read a file line by line:
file = open('notes.txt', 'r')
for line in file.read():
    print(line)
file.close()
AUsing 'r' mode instead of 'w' mode
BUsing file.read() instead of file.readlines() or iterating directly on file
CNot closing the file after reading
DMissing 'with' statement to open the file
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the for loop iteration

    The code uses file.read() which returns a single string of the whole file content.
  2. Step 2: Understand iteration over string vs lines

    Iterating over a string loops over each character, not each line. To read line by line, use file.readlines() or iterate directly on file.
  3. Final Answer:

    Using file.read() instead of file.readlines() or iterating directly on file -> Option B
  4. Quick Check:

    read() returns string, not list of lines [OK]
Quick Trick: Iterate file object or use readlines() to get lines [OK]
Common Mistakes:
  • Iterating over string instead of lines
  • Forgetting to close the file
  • Confusing read() and readline()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes