tags:

views:

88

answers:

4

I have a textfile.txt like this:

First Line
Second Line
Third Line
Fourth Line
Fifth Line
Sixth Line

How can I remove the first three lines and the last line most comfortable? Thanks!

+3  A: 
data="".join(open("textfile.txt").readlines()[3:-1])
open("newfile.txt","wb").write(data)
S.Mark
+6  A: 
lines = open('textfile.txt').readlines()
open('newfile.txt', 'w').writelines(lines[3:-1])
SilentGhost
A: 

No Python solution but since your problem is a classic, I present you a sed solution.

$ sed -n -e "4,5p" textfile.txt

Of course the address 4,5 only works for exactly your input and required output :)

A: 

this one doesn't use readlines(). Ideal for bigger sized files.

numline=3 #3 lines to skip
p=""
o=open("output.txt","a")
f=open("file")
for i in range(numline): f.next()
for line in f:
    if p: o.write(p)
    p=line
f.close()
o.close()

Since there's a sed answer, here's an awk one

$ awk 'NR>=4{if(p)print p;p=$0;}' file
Fourth Line
Fifth Line
ghostdog74
+1 for the awk :)
monojohnny