0

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!

dobbs
  • 1,089
  • 6
  • 22
  • 45
  • You're not overwriting properly. See: http://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python – Ceasar Jan 03 '17 at 20:04

1 Answers1

1

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)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139