Count number of lines in Text file in python by R4R Team

-If have a file then it might be possible that this file contain multiple lines.
-so here task is to count the number of line in exist file.

Example-
file contain the following data-
first
second
third
fourth
five

then number of line count is 5


program-

f=open('myfile.txt','w')
f.writelines("first linensecond linenthird linenfourth linenfifth line")
f.close()

#first way
f=open('myfile.txt','r')
count=0
while(f.readline()!=''):
count+=1
print("Number of lines in file is",count)
f.close()

#second way
f=open('myfile.txt','r')
s=f.read()
count=s.count("n")+1
print("Number of lines in file is",count)
f.close()


output-

Number of lines in file is 5
Number of lines in file is 5


-In this program, we insert the number of lines in the file named as 'myfile.txt' then we we try to find the numbers of line in the file in two ways.
-readline() function read the every line and go for next line, so by using this we count number of lines.
-In second way we read the whole file by read() function and store in 's' string. then we count the line break(n) in this string.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!