簡體   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