Best way to count the number of deleted lines from a file using python

I’m wondering what is the easiest way to count the number of deleted lines from a file using python. Is it taking the index of lines before and after and subtracting? Or is there a way to count the number lines deleted in a loop?

In my sample file below, I have a before user-input file and an after file that is written to exclude any lines from the user input that has negative numbers or blank spaces. I realize I will either need to count the before and after files, or find a way to count the items in the note_consider[] list.

import os, sys

inFile = sys.argv[1]
baseN = os.path.basename(inFile)
outFile = 'c:/example.txt'

#if path exists, read and write file
if os.path.exists(inFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')

    #reading and writing header
    header = inf.readline()
    outf.write(header)

    not_consider = []

    lines = inf.read().splitlines()
    for i in range(0,len(lines)):
        data = lines[i].split("\t")

        for j in range(0,len(data)):
            if (data[j] == '' or float(data[j]) < 0):
                #if line is having blank or negtive value
                # append i value to the not_consider list
                not_consider.append(i)
    for i in range(0,len(lines)):
        #if i is in not_consider list, don't write to out file
        if i not in not_consider:
            outf.write(lines[i])
            print(lines[i])
            outf.write("\n")   
    inf.close()
    outf.close()

>Solution :

This code reads a file in input and write the lines that are not empty or numbers in an output file. Was that what you expected ?

If you don’t use the information about the not_considered lines, then you can remove the associated code, and replace the for line_idx, line in enumerate(ifile.readlines()): with for line in ifile.readlines():.

The with open(<filename>, <mode>) as file: statement takes care of opening the file and closing it for you when living the scope of the statement.

def is_number(line: str):
    try:
        float(line)
        return True
    except ValueError:
        return False


with open("./file.txt", "r") as ifile, open("output.txt", "w") as ofile:
    not_considered = []

    for line_idx, line in enumerate(ifile.readlines()):
        if line == "\n" or is_number(line):
            not_considered.append(line_idx)
            continue

        ofile.write(line)

print(f"not considered  : {not_considered}")
print(f"n not considered: {len(not_considered)}")

input file:

this is

1234

a

file

with a lot

42
of empty lines

output file:

this is
a
file
with a lot
of empty lines

console output:

not considered  : [1, 2, 3, 5, 7, 9, 10]
n not considered: 7

Leave a Reply