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
  delete specific row of entries jacksfrustration 3 328 Feb-13-2024, 11:13 PM
Last Post: deanhystad
  Extracting specific file from an archive tester_V 4 433 Jan-29-2024, 06:41 PM
Last Post: tester_V
  Why can't I copy and past only ONE specific tab? NewWorldRonin 8 703 Jan-12-2024, 06:31 PM
Last Post: deanhystad
  data validation with specific regular expression shaheen07 0 296 Jan-12-2024, 07:56 AM
Last Post: shaheen07
  Find a specific keyword after another keyword and change the output sgtmcc 5 749 Oct-05-2023, 07:41 PM
Last Post: deanhystad
  Color a table cell based on specific text Creepy 11 1,860 Jul-27-2023, 02:48 PM
Last Post: deanhystad
  create a default path with idle to a specific directory greybill 0 846 Apr-23-2023, 04:32 AM
Last Post: greybill
  Printing specific values out from a dictionary mcoliver88 6 1,318 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  python print all files which contain specific word in it mg24 5 1,189 Jan-27-2023, 11:20 AM
Last Post: snippsat
  python move specific files from source to destination including duplicates mg24 3 1,052 Jan-21-2023, 04:21 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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