Skip to content

How to remove the very last character of a text file in Python?

file.truncate(file.tell - 1)
#explanation - the function truncate will resize the file to the 
#full size - 1 and that means it will remove the last character
#if you need to do that while you are reading/writing somewhere using
#seek() you can use this function ->
def get_size(fileobject):,2) # move the cursor to the end of the file
    size = fileobject.tell()
    return size
#and then
fsize = get_size(file)
file.truncate(fsize - 1)
See also  Python code snippet - How to deploy django based website using docker?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.