0 votes
1 view
in Python by (47.8k points)

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?

1 Answer

0 votes
by (107k points)

The fastest and one-liner, a solution which is also an efficient way to count lines and it takes less memory and time is as follows:-

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...