用Python删除文件最后一行

42 投票
11 回答
142039 浏览
提问于 2025-04-15 16:51

怎么用Python删除一个文件的最后一行呢?

输入文件的例子:

hello
world
foo
bar

输出文件的例子:

hello
world
foo

我写了下面的代码来找出文件有多少行,但我不知道怎么删除特定的行。

    try:
        file = open("file")
    except IOError:
        print "Failed to read file."
    countLines = len(file.readlines())

11 个回答

11

这段话虽然不涉及Python,但如果你只想完成这个任务,Python其实并不是最合适的工具。你可以使用标准的*nix工具head,然后运行下面的命令:

head -n-1 filename > newfile

这个命令会把文件名为filename的所有内容复制到新文件newfile中,除了最后一行。

88

因为我经常处理好几个GB大的文件,所以像答案中提到的那样逐个循环的方法对我来说不太管用。我用的解决方案是:

with open(sys.argv[1], "r+", encoding = "utf-8") as file:

    # Move the pointer (similar to a cursor in a text editor) to the end of the file
    file.seek(0, os.SEEK_END)

    # This code means the following code skips the very last character in the file -
    # i.e. in the case the last line is null we delete the last line
    # and the penultimate one
    pos = file.tell() - 1

    # Read each character in the file one at a time from the penultimate
    # character going backwards, searching for a newline character
    # If we find a new line, exit the search
    while pos > 0 and file.read(1) != "\n":
        pos -= 1
        file.seek(pos, os.SEEK_SET)

    # So long as we're not at the start of the file, delete all the characters ahead
    # of this position
    if pos > 0:
        file.seek(pos, os.SEEK_SET)
        file.truncate()
23

你可以使用上面的代码,然后这样做:

lines = file.readlines()
lines = lines[:-1]

这样做会给你一个包含所有行的数组,但最后一行会被省略掉。

撰写回答