Python program to count the total number of lines in a file :
In this tutorial, we will learn how to find the total number of lines in a file using python. We are using one hard-coded file name. But you can also get the file name from the user. The algorithm we are using in this program is as below :
1. Open the file in read mode. Initialize one counter as 0.
2. Using a for loop , read the file line by line .
3. Increment the counter by 1 for each line.
4. Finally, print out the counter.
Python program :
#1 file_path = r"C:\Users\userName\Documents\image.txt" #2 lines_count = 0 #3 with open(file_path,'r') as f: #4 for l in f: #5 lines_count = lines_count +1 #6 print("Total number of lines : ",lines_count)
The commented numbers in the above program denote the step-number below :
1. Store the file path in the variable file_path.
2. Initialize one variable lines_count as 0. This variable will save the count of total lines.
3. Open the file in read mode or r
4. Using one for loop, read line by line.
5. For each line, increment the value of lines_count by 1.
6. Finally, print out the total number of lines i.e. lines_count.
Example Output :
Total number of lines : 7