如何计算文本文件中的空白行数?

时间:2016-01-26 22:59:27

标签: python python-2.7 if-statement lines is-empty

import sys
import os
import glob
directory_input = raw_input("path to base directory?")
directory = directory_input

for folder in glob.glob(os.path.join(directory,"savedrecs(*).txt")):
    a = 0
    for file in glob.glob(os.path.join(folder, "savedrecs(*).txt")):
        a=sum(not line.strip() == "\n" for line in searchfile)
    print a

这是我的代码,但是a = sum(不是line.strip()==" \ n"部分不起作用,结果始终为零。

1 个答案:

答案 0 :(得分:3)

你永远不会打开文件,你的glob模式不会查找文件夹,它会查找文件,只需在用户定义的目录上查看一次,打开每个文件并sumnot line.strip()评估为是的:

import os
import glob
directory = raw_input("path to base directory?")


for fle in glob.glob(os.path.join(directory,"savedrecs*.txt")):
     with open(fle) as f:
         sm = sum(not line.strip() for line in f)
         print("{} has {} empty lines".format(fle, sm))