Home »
Python »
Python programs
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 »
TOP Interview Coding Problems/Challenges