bindo
bindo

Reputation: 87

python replacing lines in a file with nothing

I want to delete some specific lines in a file. The below code doesn't seem to work. There are no errors thrown but this code won't delete the lines that are meant to be deleted.

#!/usr/bin/python
import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("input", help="input the data in format ip:port:name", nargs='*')  
args = p.parse_args()
kkk_list = args.input # ['1.1.1.1:443:myname', '2.2.2.2:443:yourname']


def getStringInFormat(ip, port, name):
    formattedText = "HOST Address:{ip}:PORT:{port}\n"\
                    "   server tcp\n"\
                    "   server {ip}:{port} name {name}\n\n".format(ip=ip, 
                                                                port=port, 
                                                              name=name)

    return formattedText

with open("file.txt", "r+") as f:
    fileContent = f.read()

    # below two lines delete old content of file
    f.seek(0)
    f.truncate()

    for kkk in kkk_list:
        ip, port, name = re.split(":|,", kkk)

        stringNeedsToBeDeleted = getStringInFormat(ip, port, name)
        fileContent = fileContent.replace(stringNeedsToBeDeleted, "")

    f.write(fileContent)

The content of the file from which I'm trying to delete looks like following. Please note the space before 2nd and 3rd lines

------------do not delete this line------

HOST Address:1.1.1.1:PORT:443\n"\

     server tcp\n"\
     server 1.1.1.1:443 name myname1

--------------- do not delete this line either

If the script is successful the file should look like below where there is only one new line in between.

------------do not delete this line------

------------do not delete this line either ----

Any insights?

Upvotes: 0

Views: 250

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can copy the contents of your file to a list, write over the old file, mutate your list, and then write the list to the file.

import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("input", help="input the data in format ip:port:name",nargs='*')  
args = p.parse_args()
kkk_list = args.input # ['1.1.1.1:443:myname', '2.2.2.2:443:yourname']


def getStringInFormat(ip, port, name):
     formattedText = "HOST Address:{ip}:PORT:{port}\n"\
                "   server tcp\n"\
                "   server {ip}:{port} name {name}\n\n".format(ip=ip, 
                                                            port=port, 
                                                          name=name)

     return formattedText

with open("file.txt", "r+") as f:
    for kkk in kkk_list:
        ip, port, name = re.split(":|,", kkk)

        stringNeedsToBeDeleted = getStringInFormat(ip, port, name)
        fileContent = fileContent.replace(stringNeedsToBeDeleted, "")

        f.write(fileContent) #now, your file contains all the host addressed and IPs


f = open("file.txt").readlines()

contents = [i.strip('\n').split() for i in f]
new_file = open('file.txt', 'w')
new_file.write('')

new_file.write(''.join(contents[0]))
new_file.write('\n\n\n')
new_file.write(contents[''.join(len(contents)-1])))

new_file.close()

Upvotes: 0

Krupip
Krupip

Reputation: 4882

You are doing everything correct in your file editing loop, which means that if you aren't actually replacing anything its because the string you are looking for doesn't exist. Indeed, when you tell us that you are looking for this string:

------------do not delete this line------

HOST Address:1.1.1.1:PORT:443\n"\

     server tcp\n"\
     server 1.1.1.1:443 name myname1

--------------- do not delete this line either

It doesn't appear to match up with the string you are trying to match it with:

formattedText = "HOST Address:{ip}:PORT:{port}\n"\
                "   server tcp\n"\
                "   server {ip}:{port} name {name}\n\n"

Keep in mind in order to replace this string with your current code, the strings have to exactly match, in this case I don't see the \n between "HOST Addess..." and " server tcp\n"\ or the \ lines. But I suspect those were just formatting errors on your part.

If you really want to get to the root of this problem I suggest you find a string you know for certain you are trying to delete and test your code with that to make sure the strings are the same. Here is an example. If you want to find:

HOST Address:1.1.1.1:PORT:443

    server tcp

    server 1.1.1.1:443 name myname1

Then compare with your search string via:

test_string = # the string I posted above, you should probably 
              # grab this from a file for consistency. 
kkk = '1.1.1.1:443:myname'
ip, port, name = re.split(":|,", kkk)
assert ip == '1.1.1.1'
assert port == '443' 
assert name == 'myname'
stringNeedsToBeDeleted = getStringInFormat(ip, port, name)
assert stringNeedsToBeDeleted == test_string, "Error, strings are not equal!"

This should give you a clue into what the actual problem is. myname1, which I grabbed directly from your example, doesn't match up with your match string.

Upvotes: 1

Max Paymar
Max Paymar

Reputation: 708

You're opening the file in read mode 'r+'. You need to open it in write mode 'w' to write to it. Or just don't specify a mode.

Upvotes: 0

Related Questions