how to count the total number of lines in a text file using python

user2794146 picture user2794146 · Sep 25, 2013 · Viewed 127.9k times · Source

For example if my text file is:

blue
green
yellow
black

Here there are four lines and now I want to get the result as four. How can I do that?

Answer

alecxe picture alecxe · Sep 25, 2013

You can use sum() with a generator expression:

with open('data.txt') as f:
    print sum(1 for _ in f)

Note that you cannot use len(f), since f is an iterator. _ is a special variable name for throwaway variables, see What is the purpose of the single underscore "_" variable in Python?.

You can use len(f.readlines()), but this will create an additional list in memory, which won't even work on huge files that don't fit in memory.