繁体   English   中英

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

[英]Efficient way to edit the last line of a text file in Python

我有一个 Python 脚本,它创建了一个大约 300,000 行的大型 SQL 插入文件。 这个问题是文件的最后一行最终看起来像这样:

'),

这会导致 SQL 错误,因为它需要一个结束分号。

我正在寻找一种有效的方法来打开文件以在最后一行用分号替换逗号。

最简单的方法是使用标准库中内置的file.seek 看看https://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek

您只需要将 offset 设置为 0 并将 whence 设置为os.SEEK_END

我找到了这个巧妙的解决方案,它完全满足了我的需要:

# 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()

这最初是添加到问题的修订版 2中的。

暂无
暂无

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

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