dobbs
dobbs

Reputation: 1043

python replace string in a file with open()

I am trying to have separate functions that will write an ip to a new line in an existing file, and the other to remove a string in the file if it exists. Currently the code I have come up with is this:

def writeebl(_ip):
    filepath = "ebl.txt"
    with open(filepath, mode='a') as ebl:
        ebl.write(_ip)
        ebl.write("\n")


def removeebl(_ip):
    filepath = "ebl.txt"
    with open(filepath, mode='r+') as f:
            readfile = f.read()
            if _ip in readfile:
                readfile = readfile.replace(_ip, "hi")
                f.write(readfile)

writeebl("10.10.10.11")
writeebl("20.20.20.20")
removeebl("20.20.20.20")

What I assume the output should be is a file with only 10.10.10.11

First run file contents:

10.10.10.11
20.20.20.20
10.10.10.11
hi
(empty line)

Second run:

10.10.10.11
20.20.20.20
10.10.10.11
hi
10.10.10.11
hi
10.10.10.11
hi

I'm confused how this should be done. I've tried several different ways following some examples on stackoverflow, and so far I'm still stuck. Thanks in advance!

Upvotes: 0

Views: 126

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78554

You need to truncate the file before rewriting all of its content again in the removeebl function, so the stale content is wiped off before writing the updated one:

...
if _ip in readfile:
     readfile = readfile.replace(_ip, "hi")
     f.seek(0); f.truncate()
     f.write(readfile)

Upvotes: 1

Related Questions