简体   繁体   中英

Python: Replace last line in text file

I have been struggling with python script to replace last line in a text file.

I have tried several Answers example:

how-do-i-modify-the-last-line-of-a-file

efficient-way-to-edit-the-last-line-of-a-text-file-in-python

None of that worked

I am using Python 3.10

All I need is to python overwrite last line of text file example

line1
line2
line3
lastline

to be overwritten to

line1
line2
line3
overwritten_lastline

Could someone please help me?

file = open('example.txt','r')
lines = file.readlines()[:-1]
lines.append("YOUR NEW LINE")
file.close()
file = open('example.txt','w')
file.writelines(lines)

It cannot be more simpler than replacing one by one all the lines. Here's my answer that has just worked for me.

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