Search code examples
pythonif-statementis-empty

How to count empty lines in python


I am reading a file containing empty lines and words, such as "CAR" and "V3HICL3", for example. I want to write only legitimate words into another file. To do that I want to remove empty lines and words with errors( containing numerals here). I also want to count how many lines were read, removed and accepted. I am having issues capturing the empty lines. In my list, I have: car, v3hicl3, "empty". I fail to count the empty lines. Tried the isspace and line == "\n". Doesn't seem to work. How would I count that last empty line of the document?

import sys
def read():
    file_name = input("Name of the file to be read: ")
    try:
        file = open(file_name, 'r')
        lst = []
        line_num = 0
        accept_line = 0
        reject_line = 0
        empty_line = 0
        for line in file:
            line = line.strip() 
            if (len(line.strip()) == 0):
                line_num += 1
            if (line == "\n"):
                line_num += 1
            if (len(line) != 0):
                line_num += 1
            if (line.isalpha()):
                accept_line += 1
                lst.append(line)
            else:
                reject_line += 1
    print("Read", line_num, "lines")
    print("Rejected", reject_lines, "lines")
    except FileNotFoundError:
        print("open", file_name, "failure.")
        sys.exit(0)
    file.close()
    return lst, accept_line

Any input appreciated.


Solution

  • You're incrementing line_num for both empty and non-empty lines. You should be incrementing empty_lines when len(line) == 0.

    Since line_num should count all lines, increment that outside any of the conditionals.

    import sys
    
    def read():
        file_name = input("Name of the file to be read: ")
        try:
            with open(file_name, 'r') as file:
                lst = []
                line_num = 0
                accept_line = 0
                reject_line = 0
                empty_line = 0
                for line in file:
                    line_num += 1
                    line = line.strip() 
                    if (len(line) == 0):
                        empty_line += 1
                    elif (line.isalpha()):
                        accept_line += 1
                        lst.append(line)
                    else:
                        reject_line += 1
    
            print("Read", line_num, "lines")
            print("Rejected", reject_lines, "lines")
            print("Empty", empty_line, "lines")
        except FileNotFoundError:
            print("open", file_name, "failure.")
            sys.exit(0)
        return lst, accept_line