How can one delete the very last line of a file with python?
Input File example:
hello world foo bar
Output File example:
hello world foo
I've created the following code to find the number of lines in the file - but I do not know how to delete the specific line number.
try: file = open("file") except IOError: print "Failed to read file." countLines = len(file.readlines())
To delete all the lines in a file and empty the file, we can use the truncate() method on the file object. The truncate() method removes all lines from a file and sets the file pointer to the beginning of the file.
Method 1: Deleting a line using a specific position In this method, the text file is read line by line using readlines(). If a line has a position similar to the position to be deleted, it is not written in the newly created text file.
In which case: the last line is probably terminated with a new line character, if you seek to that position you can overwrite it with the new text at the end of the last line. For Python 3.2 and up, you can do the seek operation only from the beginning of a file(text file).
Because I routinely work with many-gigabyte files, looping through as mentioned in the answers didn't work for me. The solution I use:
with open(sys.argv[1], "r+", encoding = "utf-8") as file: # Move the pointer (similar to a cursor in a text editor) to the end of the file file.seek(0, os.SEEK_END) # This code means the following code skips the very last character in the file - # i.e. in the case the last line is null we delete the last line # and the penultimate one pos = file.tell() - 1 # Read each character in the file one at a time from the penultimate # character going backwards, searching for a newline character # If we find a new line, exit the search while pos > 0 and file.read(1) != "\n": pos -= 1 file.seek(pos, os.SEEK_SET) # So long as we're not at the start of the file, delete all the characters ahead # of this position if pos > 0: file.seek(pos, os.SEEK_SET) file.truncate()
You could use the above code and then:-
lines = file.readlines() lines = lines[:-1]
This would give you an array of lines containing all lines but the last one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With