简体   繁体   中英

I have to delete specific lines in text file

My query is I have to search for an ip address in a file and then delete the line that contains that ip address and also the lines above and below it. I am new to python and I have googled a lot for solutions but I couldn't get the output. Please help me out in writing the correct code. I tried with this code but failed

def delete(ip_address):
 to_be_removed_ip = ip_address
with open(alias_file) as myFile:
lines = myFile.readlines()
    for num, line in enumerate(myFile,1):
        if to_be_removed_ip in line:     
            del line[num]
            del line[num-1]
            del line[num+1]

This is the sample text file

eniq_oss_1]
eniq ip address = ['10.149.21.136']
last updated = 2018-10-23 03:00:53

[events_oss_1]
eniq ip address = ['10.149.21.144']
last updated = 2018-10-23 03:00:28

Thanks in Advance.!

It is never a good idea to manipulate an object while you are looping through it. Try creating a second object with the same content and then remove the entries from that one. In the end you can replace the first with the second and you are done.

lines = myFile.readlines()
    for num, line in enumerate(lines):
        if to_be_removed_ip in line:     
            lines[num] = ""
            lines[num-1] = ""
            lines[num+1] = ""

And now we can write lines to file and your file has been changed.

with open(alias_file,'w') as myFile:
    myFile.writelines(lines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM