samedi 10 juillet 2021

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.

Aucun commentaire:

Enregistrer un commentaire