Home > Software engineering >  how to filter out lines in text file with substring
how to filter out lines in text file with substring

Time:12-08

I have a text file with contents like this:

ADUMMY ADDRESS1
BDUMMY MEMBER
AA1400 EL DORA RD
BCARLOS
A509 W CARDINAL AVE
BJASMINE

I want a python script to count the number of lines that begin with "B" but do not contain the substring "DUMMY".

Here is what I have so far but I dont know how to do the filter in the "if" statement.

def countLinesMD(folder,f):
    file = open(folder f,"r")
    Counter = 0

    # Reading from file
    Content = file.read()
    CoList = Content.split("\n")

    for i in CoList:
        if i.startswith("B"):
            Counter  = 1
return Counter 

                                                       

CodePudding user response:

I believe you can just do this if i.startswith("B") and "DUMMY" not in i:

CodePudding user response:

Just add it to the if statement:

def countLinesMD(folder,f):
    file = open(folder f,"r")
    Counter = 0

    # Reading from file
    Content = file.read()
    CoList = Content.split("\n")

    for i in CoList:
        if i.startswith("B") and "DUMMY" not in i.split():
            Counter  = 1
return Counter 
  • Related