KnowledgeBoat Logo

Computer Science

Consider the file poemBTH.txt and predict the output of following code fragment. What exactly is the following code fragment doing ?

f = open("poemBTH.txt", "r")
nl = 0
for line in f:
    nl += 1
print(nl)

Python

Python File Handling

3 Likes

Answer

The code is calculating the number of lines present in the file poemBTH.txt.

7

Working

  1. f = open("poemBTH.txt", "r") — This line opens a file named poemBTH.txt in read mode ("r") and assigns the file object to the variable f.
  2. nl = 0 — This line initializes a variable nl to 0.
  3. for line in f: — By iterating over the file handle using a for loop as shown, we can read the contents of the file line by line.
  4. nl += 1 — Within the for loop, this statement increments the value of nl by 1 for each iteration, effectively counting the number of lines in the file.
  5. print(nl) — After the for loop completes, this statement prints the value of nl, which represents the total number of lines in the file.

Answered By

2 Likes


Related Questions