简体   繁体   中英

How to remove specific last two lines of a file?

I need to remove the following last two lines from my textfile:

ColorForeground=#000000
ColorBackground=#ffffff

The above lines are appended to the terminalrc file with the following command:

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

Thus, the last lines of the file to be modified look like this

DropdownKeepOpenDefault=TRUE
ColorForeground=#000000
ColorBackground=#ffffff

I wrote the following Python script in order to remove the last two lines of the file with .replace() method:

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)  

Yet, my script does not work as expected. The following is the result of its execution:

DropdownKeepOpenDefault=TRUE

olorForeground=#000000
ColorBackground=#ffffff

Where is the error in my Python code? How would you write such a script? Is this task doable without using regular expressions?

Read and write seperately, also don't make day a raw string, that will escape the 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM