Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete final line in file with python

Tags:

python

text

line

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()) 
like image 864
torger Avatar asked Dec 10 '09 00:12

torger


People also ask

How do I remove the last line of a text file in Python?

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.

How do you delete a specific line in a file Python?

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.

How do I change the last line of a file in Python?

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


2 Answers

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() 
like image 119
6 revs, 4 users 48% Avatar answered Oct 08 '22 18:10

6 revs, 4 users 48%


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.

like image 35
Martin Avatar answered Oct 08 '22 18:10

Martin