Skip to main content
 首页 » 编程设计

Python之在追加时删除 txt 文件的最后一行

2025年05月04日13yyy_WW

我想指定一个 raw_input 命令来删除 txt 文件的最后一行,同时附加 txt 文件。

简单代码:

while True: 
    userInput = raw_input("Data > ") 
    DB = open('Database.txt', 'a') 
    if userInput == "Undo": 
        ""Delete last line command here"" 
    else: 
        DB.write(userInput) 
        DB.close() 

请您参考如下方法:

您不能以追加模式打开文件并从中读取/修改文件中的前几行。你必须做这样的事情:

import os 
 
def peek(f): 
        off = f.tell() 
        byte = f.read(1) 
        f.seek(off, os.SEEK_SET) 
 
        return byte 
 
with open("database.txt", "r+") as DB: 
        # Go to the end of file. 
        DB.seek(0, 2) 
 
        while True: 
                action = raw_input("Data > ") 
 
                if action == "undo": 
                        # Skip over the very last "\n" because it's the end of the last action. 
                        DB.seek(-2, os.SEEK_END) 
 
                        # Go backwards through the file to find the last "\n". 
                        while peek(DB) != "\n": 
                                DB.seek(-1, os.SEEK_CUR) 
 
                        # Remove the last entry from the store. 
                        DB.seek(1, os.SEEK_CUR) 
                        DB.truncate() 
                else: 
                        # Add the action as a new entry. 
                        DB.write(action + "\n") 

编辑:感谢 Steve Jessop 建议对文件进行向后搜索而不是存储文件状态并将其序列化。

您应该注意,如果您有多个此进程正在运行,则这段代码非常很活泼(因为在向后搜索时写入文件会破坏文件)。但是,应该注意的是,您无法真正解决此问题(因为删除文件中最后一行的行为从根本上来说是一种不正当行为)。