python - 使用 Python 计算 txt 文件中的行数,不包括空行

标签 python

我想计算 .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/

相关文章:

python - Django:如何将 jinja2 变量注入(inject)模板标签然后返回输出

python - 在模块之间传递变量

python - python中的Alexa请求验证

python - 使用 Theano 在 CPU 上训练简单的 MLP 时,内存逐渐增加直至崩溃

python - 在 ffmpeg 中找不到选项

python - 返回列表的自定义 django 标签?

python - Dlib 特征数组作为 CNN 和预测的输入

python - gensim Doc2Vec vs tensorflow Doc2Vec

python - lxml xpath 如何处理xml实体

python - '属性错误 : 'module' object has no attribute 'file' ' when using oauth2client with Google Calendar