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

How do I count the number of blank lines in a text file?

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(not line.strip() == "\n" 部分不起作用,结果始终为零。

您永远不会打开文件,您的 glob 模式不会查找文件夹,它会查找文件,只需在用户定义的目录上 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))