-3

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
BLL27
  • 921
  • 5
  • 13
  • 27
  • 2
    Define 'efficient'. Time, CPU, memory efficient? Can't the Python script be altered to not emit that comma? – Martijn Pieters Feb 01 '16 at 07:46
  • 2
    Your could seek to a character before end-of-file, see https://docs.python.org/2/tutorial/inputoutput.html. But it would be better to fix the original script which creates the SQL. – cdarke Feb 01 '16 at 07:52

2 Answers2

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.

Josh Leeb-du Toit
  • 639
  • 1
  • 7
  • 13
0

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65