Search code examples
pythonpython-2.7if-statementlinesis-empty

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

This is the code I have, but the a=sum(not line.strip() == "\n" part doesn't work and the result is always zero.


Solution

  • You never open a file and your glob pattern does not look for folders, it looks for files, just glob once on the user defined directory, open each file and sum the times not line.strip() evaluates to True :

    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))