为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除文件的特​​定最后两行?

如何删除文件的特​​定最后两行?

慕桂英546537 2023-09-12 17:35:01
我需要从文本文件中删除以下最后两行: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)  然而,我的脚本没有按预期工作。其执行结果如下:DropdownKeepOpenDefault=TRUEolorForeground=#000000ColorBackground=#ffffff我的Python代码错误在哪里?你会如何写这样的脚本?不使用正则表达式是否可以完成此任务?
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

单独读取和写入,也不要创建day原始字符串,这会转义换行符 -


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)


查看完整回答
反对 回复 2023-09-12
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信