简体   繁体   中英

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM