Count number of lines in a txt file with Python excluding blank lines

A short way to count the number of non-blank lines could be:

with open('data.txt', 'r') as f:
    lines = f.readlines()
    num_lines = len([l for l in lines if l.strip(' \n') != ''])

I am surprised to see that there isn't a clean pythonic answer yet (as of Jan 1, 2019). Many of the other answers create unnecessary lists, count in a non-pythonic way, loop over the lines of the file in a non-pythonic way, do not close the file properly, do unnecessary things, assume that the end of line character can only be '\n', or have other smaller issues.

Here is my suggested solution:

with open('myfile.txt') as f:
    line_count = sum(1 for line in f if line.strip())

The question does not define what blank line is. My definition of blank line: line is a blank line if and only if line.strip() returns the empty string. This may or may not be your definition of blank line.


non_blank_count = 0

with open('data.txt') as infp:
    for line in infp:
       if line.strip():
          non_blank_count += 1

print 'number of non-blank lines found %d' % non_blank_count

UPDATE: Re-read the question, OP wants to count non-blank lines .. (sigh .. thanks @RanRag). (I need a break from the computer ...)

Tags:

Python