Remove the last line from the text file in Python

In this tutorial, you will learn about how to remove the last line from a text file in Python. Handling files in python play a crucial role in web applications.

Here we use some predefined file handling operations like creating, writing, reading, deleting files. We use these file handling operations to remove the last line from a text file in Python. Hence the first line of our script is as follows:

Open() method:

Using the open() method file operation we open an existing file using Python.

#opening the file.txt
fd=open("file.txt","r")# opening the file for reading
s=fd.read() #reading the contents of that file to sd
fd.close()  #closing the file

Input file:

pavan
kumar
ramesh

In the above program, In the first line of the script, we open the file.txt using open() method in reading format and we store the contents of the file in an fd object variable. In the second line, we store the contents of the fd object as the scriptable form in s and finally, we close the file using the close() method.
Note: In file handling operations closing the file is mandatory.

Write() method:

Using the write() method we write the contents in the file. write() method append the specified contents into the existing file.

#writing the file.txt
f=open("file.txt","w") # opening the file for writing
f.write("rebel") #writing the content into that file
f.close() #closing the file

Output:

pavan
kumar
ramesh
rebel

In the above program, In the first line of the script, we open the file.txt using open() method in writing format.
In the second step, using the write() method we have written the contents into that file and closed the file.

Example : Remove the last line from the text file in Python

#remove last line from a text line in 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()

Input file:

pavan
kumar
rebel

Output file:

pavan
kumar

Explanation:

  • In the first step of our script, we opened the file in reading format and stored its contents in the sd variable using the read() method and closed the file using the close() method.
  • In the second step of our script, Using join() and split() methods we had removed the last line from a text file and stored its contents in variable s.
  • As the third step of our script, we opened the same file again to rewrite the modified contents into the same file.
  • As the last step of our script, Using the write() method we rewritten the modified contents to the file.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *