2017-01-03 20 views
0

我想要有一個單獨的函數,將寫入一個IP到現有文件中的新行,另一個刪除文件中的字符串,如果它存在。目前,我已經拿出的代碼是這樣的:python替換打開的文件中的字符串()

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") 

我假定輸出應該是唯一10.10.10.11

首先運行文件內容的文件:

10.10.10.11 
20.20.20.20 
10.10.10.11 
hi 
(empty line) 

第二次運行:

10.10.10.11 
20.20.20.20 
10.10.10.11 
hi 
10.10.10.11 
hi 
10.10.10.11 
hi 

我很困惑這應該怎麼做。我已經嘗試了幾種不同的方法,在stackoverflow上的一些例子,到目前爲止,我仍然堅持。提前致謝!

+0

你不能覆蓋正常。請參閱:http://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python –

回答

1

您需要在removeebl功能再次重寫所有內容之前截斷該文件,所以過時的內容被寫入更新一個前抹去:

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

仍然不適合我 – dobbs

+0

答案已更新 –