gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:01:36 33 4
gpt4 key购买 nike

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

输入文件示例:

hello
world
foo
bar

输出文件示例:

hello
world
foo

我创建了以下代码来查找文件中的行数 - 但我不知道如何删除特定的行号。

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

最佳答案

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

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

关于python - 用python删除文件中的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877999/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com