Python program to count the number of lines in a file

Here, we will see a Python program to read data from a file and count the number of lines present in the file.
Submitted by Shivang Yadav, on February 21, 2021

Using file handling concepts, we can read the contents written in a file using the read () method present in Python. For reading, we can open the file using 'r' mode and then read the contents.

Algorithm:

  • Step 1: Open the file in 'r' mode for reading.
  • Step 2: Use the read file to read file contents.
  • Step 3: Increment the count if a new line is encountered.
  • Step 4: Print the file content and the print the line count.
  • Step 5: Close the file.

Program to count the number of lines in a file

F=open("drinks.dat","r")

count=0

while(True):
    b=F.read(1)
    if(b=='\n'):
        count+=1
    if(b==""):
        break
    print(b,end="")

print("Line Count " , count)

F.close()

File : drinks.dat

RedBull
Cafe Mocha
Americano
Coca Cola
Tea 

Output:

RedBull
Cafe Mocha
Americano
Coca Cola
Tea 
Line Count  5

In the above code, we have seen the counting of lines read from a file in Python. For that we have first opened a file using the open() method using 'r' mode. Then we initialize a variable count to count the number of lines in the file. Then we have used the read() method to read the file contents byte by byte. If a line break '\n' is encountered, increase the count otherwise do nothing. Print it and read the next byte. And at the end print the total count of lines in the file.

Python file handling programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.