Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading