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?
>Solution :
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.