torger torger - 23 days ago 6
Python Question

Delete final line in file via python

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

Example File:

hello
world
foo
bar


Resulatant File:

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





EDIT:

Figured it out using a variety of answers. Mostly Strawberry's and something I saw in the web - can't find the link DX.

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

Answer

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.