简体   繁体   English

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

[英]Python - Delete the last line of a txt file while appending it

I would like to specify a raw_input command to delete the last line of the txt file while appending the txt file.我想指定一个 raw_input 命令来删除 txt 文件的最后一行,同时附加 txt 文件。

Simple code:简单代码:

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

You can't open a file in append mode and read from it / modify the previous lines in the file.您无法以追加模式打开文件并从中读取/修改文件中的前几行。 You'll have to do something like this:你必须做这样的事情:

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")

EDIT: Thanks to Steve Jessop for suggesting doing a backwards search through the file rather than storing the file state and serialising it.编辑:感谢 Steve Jessop 建议对文件进行向后搜索,而不是存储文件状态并对其进行序列化。

You should note that this code is very racy if you have more than one of this process running (since writes to the file while seeking backwards will break the file).您应该注意,如果您有多个此进程在运行,则此代码非常活泼(因为在向后查找时写入文件会破坏文件)。 However, it should be noted that you can't really fix this (because the act of removing the last line in a file is a fundamentally racy thing to do).但是,应该注意的是,您无法真正解决此问题(因为删除文件中最后一行的行为从根本上来说是一件很不雅的事情)。

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

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