Asked • 05/28/19

How to get line count cheaply in Python?

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 + 1is it possible to do any better?

1 Expert Answer

By:

Nima M. answered • 11/16/19

Tutor
5 (20)

Python / Java: Object-oriented design, algorithm, data structure

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.