Bottom Page

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()
Quote
#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)
Quote
#3
Good catch,

Thank you
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  update txt file but keep a specific line 3Pinter 2 161 Dec-16-2019, 07:54 AM
Last Post: 3Pinter
  I want to log specific data to csv file akshay3210 0 123 Dec-12-2019, 06:24 PM
Last Post: akshay3210
  Highlight and remove specific string of text itsalmade 5 226 Dec-11-2019, 11:58 PM
Last Post: micseydel
  Can't seem to figure out how to delete several lines from a text file Cosmosso 9 346 Dec-10-2019, 11:09 PM
Last Post: Cosmosso
  extract specific data from a group of json-files ledgreve 3 179 Dec-05-2019, 07:57 PM
Last Post: ndc85430
  How to make a telegram bot respond to the specific word in a sentence? Metodolog 1 122 Dec-02-2019, 11:19 PM
Last Post: stullis
  Reading specific rows from CVS to Excel DavidTheGrockle 3 164 Nov-06-2019, 04:49 PM
Last Post: DavidTheGrockle
  print a word after specific word search evilcode1 8 221 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  insert value to specific line in CSV file asheru93 1 200 Oct-21-2019, 03:37 PM
Last Post: Larz60+
  loop through range until reach size and exclude specific symbol pino88 3 209 Sep-23-2019, 02:32 AM
Last Post: perfringo

Forum Jump:


Users browsing this thread: 1 Guest(s)