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)
Answer
The code is calculating the number of lines present in the file poemBTH.txt.
7
Working
f = open("poemBTH.txt", "r")
— This line opens a file namedpoemBTH.txt
in read mode ("r") and assigns the file object to the variablef
.nl = 0
— This line initializes a variablenl
to 0.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.nl += 1
— Within thefor
loop, this statement increments the value ofnl
by 1 for each iteration, effectively counting the number of lines in the file.print(nl)
— After the for loop completes, this statement prints the value ofnl
, which represents the total number of lines in the file.
Related Questions
What is the following code doing ?
file = open("contacts.csv", "a") name = input("Please enter name.") phno = input("Please enter phone number.") file.write(name + "," + phno + "\n")
Consider the file "contacts.csv" created in above Q. and figure out what the following code is trying to do?
name = input("Enter name :") file = open("contacts.csv", "r") for line in file: if name in line: print(line)
Write a method in Python to read the content from a text file diary.txt line by line and display the same on screen.
Write a method in Python to write multiple line of text contents into a text file mylife.txt.line.