简体   繁体   English

在 Python 中编辑文本文件最后一行的有效方法

[英]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.我有一个 Python 脚本,它创建了一个大约 300,000 行的大型 SQL 插入文件。 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.这会导致 SQL 错误,因为它需要一个结束分号。

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.最简单的方法是使用标准库中内置的file.seek Take a look at https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek看看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 .您只需要将 offset 设置为 0 并将 whence 设置为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.这最初是添加到问题的修订版 2中的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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