Count number of lines in a text file in Python (original) (raw)
Last Updated : 19 Dec, 2025
Given a text file, the task is to count the number of lines it contains. This is a common requirement in many applications such as processing logs, analyzing datasets, or validating user input.
**Example: Input file (myfile.txt)

**Output: Total Number of lines: 4
Below are the methods that we will used to count the lines in a text file:
Using a Loop and sum() Function
Count lines efficiently by summing 1 for each line while iterating through the file.
Python `
with open("myfile.txt", 'r') as fp: lines = sum(1 for line in fp) print('Total Number of lines:', lines)
`
**Output
Total Number of lines: 4
**Explanation: lines = sum(1 for line in fp) Counts each line efficiently without loading the whole file.
Using enumerate()
enumerate() method adds a counter to an iterable. We can use it to count lines efficiently.
Python `
with open("myfile.txt", 'r') as fp: for count, line in enumerate(fp, 1): pass print('Total Number of lines:', count if 'count' in locals() else 0)
`
**Output
Total Number of lines: 4
**Explanation:
- **for count, line in enumerate(fp, 1): pass: Iterates over each line, counting lines starting from 1 using enumerate().
- **print('Total Number of lines:', count if 'count' in locals() else 0): Prints the total number of lines; safely handles empty files.
Using a Loop and Counter
Count lines by iterating through the file line by line with a simple counter.
Python `
counter = 0 with open("myfile.txt", "r") as file: for line in file: counter += 1 print("Total Number of lines in the file:", counter)
`
**Output
Total number of lines in the file: 4
**Explanation: for line in file: counter += 1: Iterates over each line in the file and increments the counter.
Using readlines()
readlines() method reads all lines in a file at once and returns them as a list. This method is suitable for small files.
Python `
with open("myfile.txt", 'r') as fp: lines = len(fp.readlines()) print('Total Number of lines:', lines)
`