Q:

Python program to count the number of lines in a file

belongs to collection: Python file handling programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to read first N character from each... >>
<< Python program to delay printing of lines from a f...