2
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.

  • 4
    Can you show the full code, and the exact results? E.g. how are you doing the counting, how are you opening the file, how are you reading the lines. – Tom Dalton Jan 26 '16 at 23:01
  • 3
    `sum(not line.strip() for line in f)` – Padraic Cunningham Jan 26 '16 at 23:01
  • 2
    Your first approach should work. Give an input file for which it does not. – timgeb Jan 26 '16 at 23:02
  • What about "\n\n" (how much you can find this string in the file )? And some logic for the last row (if the file ends with \n) – YoniXw Jan 26 '16 at 23:02
  • The problem is that the result always gives 0, but the files have many blocks of text and many empty lines that separate them. I can't see what the error is. – NAZLI UGUR KOYLUOGLU Jan 26 '16 at 23:25
  • Do you *have* to do this in Python? Your system command line likely has something that will handle this much faster, such as searching for "^$" with **awk** under UNIX/Linux. – Prune Jan 26 '16 at 23:31
  • `line.strip() == "\n"` will never evaluate to `True`, because the `strip()` will always remove the `\n` if it's the only thing left. – glibdud Jan 26 '16 at 23:56

1 Answers1

3

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))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thanks! One question, what difference does line.strip() and line.strip()=="" make, and what does the strip command actually do? – NAZLI UGUR KOYLUOGLU Jan 27 '16 at 01:18
  • Both are equivalent, like when checking for an empty list, tuple etc.. You don't have to explicitly comprehension to an empty string , strip will strip any newline so if after stripping you have an empty string you know you have a blank line. – Padraic Cunningham Jan 27 '16 at 01:41