使用python删除文件中的最后一行 [英] Delete final line in file with python
本文介绍了使用python删除文件中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用python删除文件的最后一行?
How can one delete the very last line of a file with python?
输入文件示例:
hello
world
foo
bar
输出文件示例:
hello
world
foo
我创建了以下代码来查找文件中的行数-但我不知道如何删除特定的行号.我是python的新手-如果有更简单的方法-请告诉我.
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. I'm new to python - so if there is an easier way - please tell me.
try:
file = open("file")
except IOError:
print "Failed to read file."
countLines = len(file.readlines())
我用各种各样的答案弄清楚了:大多数是草莓的,还有我在网上看到的东西(对不起,我找不到链接).
I figured it out using a variety of answers: Mostly Strawberry's and something I saw in the web (sorry, I can't find the link).
#!/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()
推荐答案
您可以使用上面的代码,然后:-
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屋!
查看全文