How to Get the Number of Lines in a File in Python


If you need to get the number of lines in a file, or the line count total from a file, using Python, then you can use one of the following options:

Option 1 – Using open() and sum()

with open('directory/file.txt') as myfile:
    total_lines = sum(1 for line in myfile)

print(total_lines)

Option 2 – Using mmap

import mmap

with open('directory/file.txt', "r+") as myfile:
    mm = mmap.mmap(myfile.fileno(), 0)
    total_lines = 0

    while mm.readline():
        total_lines += 1

print(total_lines)

Option 3 – Using file.read()

lines = 0
size = 1024 * 1024

with open(r'directory/file.txt', "r+") as myfile:
    read_file = myfile.read

    buffer = read_file(size)
    
    while buffer:
        lines += buffer.count('\n')
        buffer = read_file(size)

if (lines != 0):
    lines += 1

print(lines)