簡體   English   中英

如何刪除文件的特​​定最后兩行?

[英]How to remove specific last two lines of a file?

我需要從我的文本文件中刪除以下最后兩行:

ColorForeground=#000000
ColorBackground=#ffffff

使用以下命令將上述行附加到terminalrc文件:

echo -e "ColorForeground=#000000\nColorBackground=#ffffff">>/home/jerzy/.config/xfce4/terminal/terminalrc

因此,要修改的文件的最后幾行如下所示

DropdownKeepOpenDefault=TRUE
ColorForeground=#000000
ColorBackground=#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)  

然而,我的腳本沒有按預期工作。 下面是它的執行結果:

DropdownKeepOpenDefault=TRUE

olorForeground=#000000
ColorBackground=#ffffff

我的 Python 代碼中的錯誤在哪里? 你會怎么寫這樣的劇本? 這個任務不使用正則表達式是否可行?

讀取和寫入seperately,也不讓day一個原始字符串,將難逃NEWLINE-

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM