Python Forum
Delete specific lines contain specific words - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Delete specific lines contain specific words (/thread-22224.html)



Delete specific lines contain specific words - mannyi - Nov-04-2019

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()



RE: Delete specific lines contain specific words - baquerik - Nov-04-2019

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)



RE: Delete specific lines contain specific words - mannyi - Nov-04-2019

Good catch,

Thank you