PythonMastery
Python programs · Files · beginner

Count lines in a file in Python

Count the lines in a text file without loading it all into memory, then count words and characters too, like the wc command.

To count the lines in a file, loop over the file and add 1 for each line. This reads one line at a time, so it also works for very large files.

The program

python
with open("story.txt", "w", encoding="utf-8") as f:
    f.write("Margaret wrote the code.\n")
    f.write("The code went to the Moon.\n")
    f.write("The landing was a success.\n")

with open("story.txt", encoding="utf-8") as f:
    line_count = sum(1 for line in f)

print(f"Lines: {line_count}")
output
Lines: 3

How it works

Lines, words and characters

The Unix command wc prints these three numbers. Here is the same thing in Python:

python
with open("story.txt", "w", encoding="utf-8") as f:
    f.write("Margaret wrote the code.\n")
    f.write("The code went to the Moon.\n")
    f.write("The landing was a success.\n")

lines = words = chars = 0
with open("story.txt", encoding="utf-8") as f:
    for line in f:
        lines += 1
        words += len(line.split())
        chars += len(line)

print(f"Lines: {lines}, words: {words}, characters: {chars}")
output
Lines: 3, words: 15, characters: 79

line.split() with no argument splits on any run of spaces and ignores the \n, so it gives the words of the line. The character count includes the three \n characters.

Learn the idea: Files: Reading and Writing to Disk, File I/O, Pathlib, and Large Files, Loops: for, while, and the Pythonic Patterns