Given that empty lines only contain the new line character, it would be much faster to avoid calling str.strip , which creates a new line, but instead checks to see if the line contains only spaces with str.isspace , and then skips it:
with open('data.txt') as f: non_blank_lines = sum(not line.isspace() for line in f)
Demo:
from io import StringIO s = '''apple orange pear hippo donkey''' non_blank_lines = sum(not line.isspace() for line in StringIO(s)))
You can use str.isspace with itertools.groupby to count the number of contiguous lines / blocks in a file:
from itertools import groupby no_paragraphs = sum(k for k, _ in groupby(StringIO(s), lambda x: not x.isspace())) print(no_paragraphs)
Moses koledoye
source share