我想计算 .txt 文件中的行数,看起来像这样:
apple
orange
pear
hippo
donkey
其中有用于分隔 block 的空行。根据上述示例,我正在寻找的结果是五(行)。
我怎样才能做到这一点?
作为奖励,最好知道有多少 block /段落。因此,根据上面的示例,这将是两个 block 。
最佳答案
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
更新:重新阅读问题,OP 想要计算非空白行..(叹息..感谢@RanRag)。 (我需要离开电脑休息一下......)
关于python - 使用 Python 计算 txt 文件中的行数,不包括空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10673560/