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

0 min read 115 words

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags