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