How to get line count of a large file cheaply in Python?

SilentGhost picture SilentGhost · May 10, 2009 · Viewed 889.4k times · Source

I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise?

At the moment I do:

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

is it possible to do any better?

Answer

Kyle picture Kyle · Jun 19, 2009

One line, probably pretty fast:

num_lines = sum(1 for line in open('myfile.txt'))