Python program to count the number of lines in a file

Python | Count number of lines in a text file: In this tutorial, we will learn how to count the number of lines in a text file. Learn with its steps and examples. By Shivang Yadav Last updated : July 05, 2023

Problem statement

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.

How to count number of lines in a text file?

The steps/algorithm to count the number of lines in a text file are as follows,

  • 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.

Python program to count number of lines in a text 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

Explanation

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.