Skip to content

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)
Code language: Python (python)

Option 2 – Using mmap

import mmap with open('directory/file.txt', "r+") as myfile: mm = mmap.mmap(myfile.fileno(), ) total_lines = while mm.readline(): total_lines += 1 print(total_lines)
Code language: Python (python)

Option 3 – Using

lines = size = 1024 * 1024 with open(r'directory/file.txt', "r+") as myfile: read_file = buffer = read_file(size) while buffer: lines += buffer.count('\n') buffer = read_file(size) if (lines != ): lines += 1 print(lines)
Code language: Python (python)

See also  How to Get Last Digit of a Large Number in C
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x