Python Forum
Delete specific lines contain specific words
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete specific lines contain specific words
#1
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()
Reply
#2
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)
Reply
#3
Good catch,

Thank you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Solved] Trying to read specific lines from a file Laplace12 7 191 11 hours ago
Last Post: Laplace12
  Extract specific sentences from text file Bubly 3 254 May-31-2021, 06:55 PM
Last Post: Larz60+
  Moving specific files then unzipping/decompressing christophereccles 2 239 Apr-24-2021, 04:25 AM
Last Post: ndc85430
  Running loop at specific frequency mdsousa 3 483 Apr-21-2021, 11:22 AM
Last Post: jefsummers
  How to extract specific key value pair from string? aditi06 0 355 Apr-15-2021, 06:26 PM
Last Post: aditi06
  Printing a specific line from a JSON serpiente 4 591 Mar-14-2021, 07:27 PM
Last Post: buran
  Annotating plot bar from values of other a specific column celinafregoso99 0 341 Mar-10-2021, 03:19 PM
Last Post: celinafregoso99
  How to append a value to specific excel cell using openpyxl hobbyist 0 611 Mar-05-2021, 07:14 PM
Last Post: hobbyist
  Find specific file in an archive tester_V 8 681 Feb-13-2021, 06:13 PM
Last Post: tester_V
  read logfile between two specific strings FelixReiter 6 519 Jan-04-2021, 02:26 PM
Last Post: FelixReiter

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020