Python Forum

Full Version: Delete specific lines contain specific words
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

Have this code to delete line contain name "sandy15" however it delete others lines two and always keep the last line in the test

Before the code:

sandy15
sandy14
manny15
hello15

After the code:

hello15

Thx in advanced

here is the code:
pdu_file = "/labhome/manny/pdu_file.orig"
name = "sandy15"

def rm_pdu_record():
    with open(pdu_file, 'r') as f:
        lines = f.readlines()
    with open (pdu_file, 'w') as f:
        for line in lines:
            if name in line.strip("\n"):
                continue
        f.write(line)
        
rm_pdu_record()
The f.write must be inside the loop, otherwise you only handle the last line

for line in lines:
    if name in line.strip("\n"):
        continue
    f.write(line)
Good catch,

Thank you