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()

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

print(total_lines)

Option 2 – Using mmap

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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)