我需要從文本文件中刪除以下最后兩行:ColorForeground=#000000ColorBackground=#ffffffterminalrc使用以下命令將以上行附加到文件中:echo -e "ColorForeground=#000000\nColorBackground=#ffffff">>/home/jerzy/.config/xfce4/terminal/terminalrc因此,要修改的文件的最后幾行如下所示DropdownKeepOpenDefault=TRUEColorForeground=#000000ColorBackground=#ffffff我編寫了以下 Python 腳本,以便使用.replace()方法刪除文件的最后兩行:day = r"ColorForeground=#000000\nColorBackground=#ffffff"file = r"/home/jerzy/.config/xfce4/terminal/terminalrc"with open(file) as f: content = f.read() content = content.replace(day, "") with open(file, 'r+') as f2: f2.write(content) 然而,我的腳本沒有按預(yù)期工作。其執(zhí)行結(jié)果如下:DropdownKeepOpenDefault=TRUEolorForeground=#000000ColorBackground=#ffffff我的Python代碼錯誤在哪里?你會如何寫這樣的腳本?不使用正則表達(dá)式是否可以完成此任務(wù)?
1 回答

慕容708150
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個贊
單獨(dú)讀取和寫入,也不要創(chuàng)建day原始字符串,這會轉(zhuǎn)義換行符 -
day = "ColorForeground=#000000\nColorBackground=#ffffff\n"
with open(file, 'r') as f:
content = f.read()
content = content.replace(day, "")
with open(file, 'w') as f:
f.write(content)
添加回答
舉報(bào)
0/150
提交
取消