remove last line from file python code example

Example 1: python delete the last line of console

print("This message will remain")
print("This message will be deleted", end="\r")
#NOTE: If you run it in IDLE by pressing F5, the shell will still display#
#both messages, however, if you run the program by double clicking#
#then the ouput console will delete it!#

Example 2: remove last line of text file python

fd=open("file.txt","r")
d=fd.read()
fd.close()
m=d.split("\n")
s="\n".join(m[:-1])
fd=open("file.txt","w+")
for i in range(len(s)):
    fd.write(s[i])
fd.close()

Tags:

Misc Example