HOWTO · Python

How to Get Number of Lines in a File in Python

Learn how to count file lines in Python with iteration, readlines(), chunked reads, and mmap, and choose an approach based on memory use and line endings.

On this page

To count the lines in a text file, iterate over the open file and add one for each line. This reads incrementally, so it is a good general choice even when the file is too large to fit in memory. Python’s text-file iterator recognizes line endings and returns a final unterminated line as a line too.

Run this example:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    path = Path(directory) / "notes.txt"
    path.write_text("alpha\nbeta\ngamma\n", encoding="utf-8")

    with path.open(encoding="utf-8") as file:
        line_count = sum(1 for line in file)

    print(line_count)
3

The with statement closes the file even if reading raises an error. sum() consumes the generator as the file is read; it does not build a list of all lines. For a file supplied by a user, replace the temporary path with that file’s path. If it cannot be opened, Python reports the underlying file error, such as FileNotFoundError. (open())

Count Lines by Iterating Over a File

A for loop gives the same incremental behavior when you want to do something with each line as you count it. The file object yields one text line at a time, including its line ending when present. The final line still counts if it has no trailing newline.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    path = Path(directory) / "records.txt"
    path.write_text("first\nsecond\nthird", encoding="utf-8")

    line_count = 0
    with path.open(encoding="utf-8") as file:
        for line in file:
            line_count += 1

    print(line_count)
3

This approach uses memory for the current line rather than for the whole file. It is usually the clearest choice for ordinary text files. The generator form above is shorter when counting is the only task.

Count Lines with readlines()

readlines() reads every line and returns a list. Its length is the line count, but the list and its strings occupy memory proportional to the file size. Use it when you also need the lines later and the file comfortably fits in memory; for counting alone, iteration avoids retaining them all.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    path = Path(directory) / "records.txt"
    path.write_text("first\nsecond\nthird\n", encoding="utf-8")

    with path.open(encoding="utf-8") as file:
        lines = file.readlines()

    print(len(lines))
3

Count Lines in Chunks with read()

For a large file where you want bounded-size reads, open it in binary mode and count line-ending bytes across chunks. This example treats LF, CRLF, and lone CR as line endings, including when a CRLF pair straddles two chunks. A final byte that is not a line ending starts an unterminated final line. This byte-oriented approach assumes an ASCII-compatible encoding such as UTF-8; for text with another encoding or Python’s decoded text-line behavior, prefer text iteration.

from pathlib import Path
from tempfile import TemporaryDirectory

chunk_size = 4
with TemporaryDirectory() as directory:
    path = Path(directory) / "records.txt"
    path.write_bytes(b"one\r\ntwo\nthree\rfour")

    line_count = 0
    previous = None
    last = None
    with path.open("rb") as file:
        while chunk := file.read(chunk_size):
            for byte in chunk:
                if byte == 10:
                    if previous != 13:
                        line_count += 1
                elif byte == 13:
                    line_count += 1
                previous = byte
                last = byte

    if last is not None and last not in (10, 13):
        line_count += 1
    print(line_count)
4

The carry state (previous and last) preserves the information needed at chunk boundaries and at end of file. Each read is limited to chunk_size, so memory use stays bounded. Choose a larger chunk to reduce the number of read operations. If the file can change while it is being counted, the result may reflect a mixture of its contents; coordinate access when a consistent snapshot matters.

Count Lines with mmap.mmap()

mmap.mmap() creates a memory-mapped view of a file; it is not a line-counting function. Mapping can be useful when a workload needs direct access to a large file, but it adds setup and platform considerations. For a simple count, streaming iteration is usually easier. The example uses a read-only mapping and counts LF bytes: each LF ends a record, and a final unterminated sequence of bytes adds one more. This treats CRLF as one ending because it contains LF, but does not treat a lone CR as a line ending.

import mmap
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    path = Path(directory) / "records.txt"
    path.write_bytes(b"first\nsecond\nthird")

    with path.open("rb") as file:
        if path.stat().st_size == 0:
            line_count = 0
        else:
            with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
                line_count = 0
                position = 0
                while True:
                    position = mapped.find(b"\n", position)
                    if position == -1:
                        break
                    line_count += 1
                    position += 1
                if mapped[-1] != 10:
                    line_count += 1

    print(line_count)
3

A zero-length file cannot be mapped with a length of zero, so check its size first. The nested context managers release both the mapping and file handle. Mapping support and behavior depend on the operating system and file; use a regular streaming read if mapping is unavailable or its setup is not worthwhile. This byte-based example counts LF-delimited records, including a final record without a trailing LF; it does not count lone CR bytes as line endings. Use text iteration when you need decoded text and Python’s universal-newline handling.

Choose a Line-Counting Method

Use sum(1 for line in file) or a for loop for a straightforward count with low memory use. Choose readlines() when the list itself is useful and fits in memory. Use chunked read() when you specifically need bounded binary reads and can define how bytes represent line endings. Consider mmap.mmap() only when memory mapping suits the broader workload; it does not make the count inherently faster and requires a nonempty file and reliable cleanup.

Text iteration applies Python’s universal-newline handling: \n, \r\n, and \r are recognized as line endings when a file is opened in the default text mode. A terminal line ending does not create an additional blank line after the final record. An empty file yields a count of zero, while nonempty text without a final line ending still has a final line. These semantics differ from a simple count of b"\n", which misses lone CR endings and does not account for a final unterminated line. Pick the method that matches the file’s encoding and the exact line definition your application needs.