使用python删除文件中的最后一行

tor*_*ger 30 python text line

如何用python删除文件的最后一行?

输入文件示例:

hello
world
foo
bar
Run Code Online (Sandbox Code Playgroud)

输出文件示例:

hello
world
foo
Run Code Online (Sandbox Code Playgroud)

我创建了以下代码来查找文件中的行数 - 但我不知道如何删除特定的行号.我是python的新手 - 所以如果有更简单的方法 - 请告诉我.

    try:
        file = open("file")
    except IOError:
        print "Failed to read file."
    countLines = len(file.readlines())
Run Code Online (Sandbox Code Playgroud)

编辑:

我想出了各种各样的答案:主要是草莓和我在网上看到的东西(对不起,我找不到链接).

#!/usr/bin/env python

import os, sys

readFile = open("file")

lines = readFile.readlines()

readFile.close()
w = open("file",'w')

w.writelines([item for item in lines[:-1]])

w.close()
Run Code Online (Sandbox Code Playgroud)

Saq*_*qib 66

因为我经常使用许多千兆字节的文件,所以在答案中提到的循环对我来说不起作用.我使用的解决方案:

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()
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案.使用"with"语句保存一行:) (4认同)
  • 当在mac和windows上使用的文件上使用此方法时,我遇到了一些兼容性问题(使用Py3),因为内部Mac使用与Windows不同的行终止符(使用2:cr和lf).解决方案是以二进制读取模式("rb +")打开文件,并搜索二进制换行符b"\n". (2认同)

Mar*_*tin 13

你可以使用上面的代码然后: -

lines = file.readlines()
lines = lines[:-1]
Run Code Online (Sandbox Code Playgroud)

这将为您提供包含除最后一行之外的所有行的数组.

  • 这适用于大文件吗?数千行? (3认同)
  • 对于大于一兆字节或两兆字节的文件,它可能无法正常工作.取决于你对"井"的定义.对于几千行的任何桌面使用它应该是完全正常的. (3认同)

Dan*_*ead 7

假设您必须在 Python 中执行此操作,并且您有一个足够大的文件,列表切片是不够的,您可以通过该文件一次完成:

last_line = None
for line in file:
    if last_line:
        print last_line # or write to a file, call a function, etc.
    last_line = line
Run Code Online (Sandbox Code Playgroud)

不是世界上最优雅的代码,但它可以完成工作。

基本上它通过 last_line 变量缓冲文件中的每一行,每次迭代输出前一次迭代行。


Pet*_*ter 6

这不是使用python,但如果这是你想要的唯一任务,那么python是错误的工具.您可以使用标准的*nix实用程序head,然后运行

head -n-1 filename > newfile
Run Code Online (Sandbox Code Playgroud)

它会将除文件名的最后一行以外的所有文件复制到newfile.

  • 这在Mac OSX上不起作用:head:非法行数 - -1 (6认同)

Moj*_*Moj 5

这是我为Linux用户提供的解决方案:

import os 
file_path = 'test.txt'
os.system('sed -i "$ d" {0}'.format(file_path))
Run Code Online (Sandbox Code Playgroud)

无需在 python 中读取和迭代文件。