Python程序教程

您现在的位置是:首页 >  Python

当前栏目

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

python,删除,最后,一行,文本,文件
2025-03-25 08:59:31 时间

大家好,又见面了,我是你们的朋友全栈君。

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

输入文件示例:

hello

world

foo

bar

输出文件示例:

hello

world

foo

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

try:

file = open(“file”)

except IOError:

print “Failed to read file.”

countLines = len(file.readlines())

编辑:

我用各种各样的答案找出来:大多数草莓和我在网上看到的东西(对不起,我找不到链接)。

#!/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()

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/144881.html原文链接:https://javaforall.cn