VOOZH about

URL: https://www.geeksforgeeks.org/python/count-number-of-lines-in-a-text-file-in-python/

⇱ Count number of lines in a text file in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count number of lines in a text file in Python

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)

👁 Image

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.

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.

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.

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.

Output

Total Number of lines: 4

Explanation: lines = len(fp.readlines()) Reads all lines into a list and counts them.

Related Articles:

Comment