Python - 删除txt文件的最后一行

时间:2015-09-03 00:17:50

标签: python

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

简单代码:

newdd = function toObject(arr) {
    var a =[];
    for (var i = 0; i < arr.length; ++i) {
        var rv = {};
        rv["data"] = arr[i];
        a.push(rv);
    }

    return a;
 }

1 个答案:

答案 0 :(得分:1)

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

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建议对文件进行向后搜索,而不是存储文件状态并将其序列化。

如果您正在运行多个此进程,则应注意此代码非常 racy(因为在向后搜索时写入文件会破坏文件)。但是,应该注意的是,你无法真正解决这个问题(因为删除文件中最后一行的行为是一件非常有趣的事情)。

相关问题