Open In App

Remove last character from the file in Python

Last Updated : 26 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a text file our task is to delete the last character from the file using Python

Example:

Input: File before removing the last character GeeksforGeeks
Output: File after removing the last character GeeksforGeek

Example 1: Using the seek and truncate function

Python3




with open('geeks.txt','w') as file_reader:
    file_reader.write("GeeksforGeeks")
print("File before removing the last character",open('geeks.txt').read())
with open('geeks.txt', 'rb+') as fh:
    fh.seek(-1, 2)
    fh.truncate()
print("File after removing the last character",open('geeks.txt').read())


Output:

After removing the last character from the file.

After removing the last character from the file.

Explanation:

Here we are opening the file with ‘w’ mode i.e. with the write mode because if the file is not present then it is created automatically without raising any error, then we write some text in the file and finally we are fetching the text that is present in the file. Here we are opening the already created text file with the ‘rb+’ mode which opens a file for both reading and writing in binary format then we seek the last character from the file by -1 and then truncate the last character and updating the file. Here we are checking whether the truncate function has worked correctly or not and finally fetching the result.

Example 2: Modifying the string and writing in the file again

Python3




L = ["Geeks\n", "for\n", "Geeks"]
  
# writing in the file
  
file1 = open('geeks.txt', 'w')
file1.writelines(L)
file1.close()
  
# Using readlines()
  
file1 = open('geeks.txt', 'r+')
Lines = file1.readlines()
file1.close()
  
# Writing the modifiyed line in the file
  
Lines[-1] = Lines[-1][:-1]
file1 = open('geeks.txt', 'w')
file1.writelines(Lines)
file1.close()


Output:

Modified file.

Modified file.

Explanation:

Here we are simply writing in a file and then fetching those lines, finally removing the last character from the last line which is basically our task and then modifying the file with the updated lines.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads