Consider the following Python code and answer the question given below: with…
2023
Consider the following Python code and answer the question given below: with open("NOTES.TXT", "r") as F: Line = F.readlines() Which of the following Python statements will find and display the number of lines present in the file "NOTES.TXT"?
- A.
print(len(LINE))
- B.
print(LINE.count())
- C.
print(LINE.count('\n'))
- D.
print(LINE.len())
Attempted by 1628 students.
Show answer & explanation
Correct answer: A
The readlines() method returns a list where each element is one line from the file. To find the number of lines, use len() on this list.
Note that Python is case-sensitive. The variable is named Line (with a capital L), so the correct statement is print(len(Line)).
Why the other options are incorrect:
print(LINE.count()) — count() requires an argument; without it, this raises an error.
print(LINE.count('\n')) — this counts how many list elements are exactly the string '\n', not the number of lines.
print(LINE.len()) — len is a built-in function, not a method; it cannot be called as a list method.