-2

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?

rks
  • 9
  • 1
  • Please explain more about what you mean by "none of that worked". Surely reading all lines of the file into a list, replacing the last element of the list, and writing all elements of the list as lines to a new file, as described [here](https://stackoverflow.com/a/328196) will work. – mkrieger1 Apr 28 '22 at 13:22
  • @mkrieger1 exactly seek(-len(os.linesep), os.SEEK_END) did not worked and I got error – rks Apr 28 '22 at 13:24
  • That's not what the answer I was referring to suggests to do (it's another answer). But it should still work. If you don't tell us the exact code you used and the error message you got, we can't explain to you what the problem was. – mkrieger1 Apr 28 '22 at 13:27

1 Answers1

1
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.

acalasanzs
  • 146
  • 1
  • 4