Count the Number of Lines in a File in Python

To count the number of lines in a file in Python, we can use different methods such as reading the file line by line, using the readlines() method, or iterating over the file object.

In this tutorial, we will explore multiple approaches to count lines in a file with examples.


Examples for Counting the Number of Lines in a File

1. Using a For Loop to Count Lines in File

We can count the number of lines in a file by iterating over each line using a for loop and maintaining a counter.

main.py

</>
Copy
# Open the file in read mode
with open("sample.txt", "r") as file:
    line_count = sum(1 for line in file)

# Print the number of lines
print("Total number of lines:", line_count)

Explanation:

  1. The open() function is used to open sample.txt in read mode.
  2. The sum() function is used with a generator expression that iterates over each line in the file, adding 1 for each line.
  3. Finally, line_count stores the total number of lines, which is printed.

Output:

2. Using readlines() Method in Count Lines in a File

The readlines() method reads all lines into a list, allowing us to count them using len().

main.py

</>
Copy
# Open the file and read all lines
with open("sample.txt", "r") as file:
    lines = file.readlines()

# Count the number of lines
line_count = len(lines)

# Print the number of lines
print("Total number of lines:", line_count)

Explanation:

  1. The readlines() method reads all lines from the file and stores them in a list.
  2. The len() function calculates the number of elements (lines) in the list.
  3. The result is stored in line_count and printed.

Output:

3. Using enumerate() Function to Count Lines in File

The enumerate() function provides an efficient way to count the number of lines while iterating through a file.

main.py

</>
Copy
# Open the file and use enumerate to count lines
with open("sample.txt", "r") as file:
    line_count = sum(1 for _, _ in enumerate(file, 1))

# Print the number of lines
print("Total number of lines:", line_count)

Explanation:

  1. The enumerate() function iterates over the file, assigning an index to each line (starting from 1).
  2. The sum() function adds 1 for each line encountered.
  3. The result is stored in line_count and printed.

Output:

4. Using While Loop to Count Lines in a File

We can also use a while loop to read each line manually and count them.

main.py

</>
Copy
# Open the file
with open("sample.txt", "r") as file:
    line_count = 0
    while file.readline():
        line_count += 1

# Print the number of lines
print("Total number of lines:", line_count)

Explanation:

  1. The readline() method reads one line at a time.
  2. A while loop keeps reading lines until the end of the file is reached.
  3. The line_count variable is incremented for each line read.
  4. Finally, the number of lines is printed.

Output:

Conclusion

In this tutorial, we have covered multiple ways to count the number of lines in a file:

  1. Using a for loop: The most memory-efficient method.
  2. Using readlines(): Simple but loads the entire file into memory.
  3. Using enumerate(): An alternative approach leveraging built-in functions.
  4. Using a while loop: Reads one line at a time, similar to a for loop.

The choice of method depends on the file size and efficiency requirements. The for loop approach is the most recommended for large files.