'Efficient way to edit the last line of a text file in Python

I have a Python script which creates a large SQL insert file of about 300,000 lines. The problem with this is that the last line of the file ends up looking like this:

'),

Which results in a SQL error as it is expecting a closing semicolon.

I am looking for an efficient way to open the file to replace the comma with a semicolon on the last line.



Solution 1:[1]

The simplest way is to use file.seek which is built into the standard library. Take a look at https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek

You simply need to set offset to 0 and the whence to os.SEEK_END.

Solution 2:[2]

I found this neat solution which did exactly what I needed:

# Get the last line in the file and replace the comma with a semicolon to close the SQL statement.
with open(file_to_execute, 'rb+') as filehandle:
    filehandle.seek(-1, os.SEEK_END)
    filehandle.truncate()
    filehandle.write(";")
    filehandle.close()

This was originally added to Revision 2 of the question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josh Leeb-du Toit
Solution 2