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