用python删除文件中的最后一行 [英] Delete final line in file with python

查看:130
本文介绍了用python删除文件中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can one delete the very last line of a file with python?

输入文件示例:

hello
world
foo
bar

输出文件示例:

hello
world
foo

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

I've created the following code to find the number of lines in the file - but I do not know how to delete the specific line number.

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

推荐答案

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

You could use the above code and then:-

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

这会给你一个包含除最后一行之外的所有行的行数组.

This would give you an array of lines containing all lines but the last one.

这篇关于用python删除文件中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆