24

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
creativz
  • 10,369
  • 13
  • 38
  • 35

5 Answers5

42
with open('textfile.txt') as old, open('newfile.txt', 'w') as new:
    lines = old.readlines()
    new.writelines(lines[3:-1])
tripleee
  • 175,061
  • 34
  • 275
  • 318
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
19

This one doesn't use readlines() so it is 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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
5
data="".join(open("textfile.txt").readlines()[3:-1])
open("newfile.txt","wb").write(data)
YOU
  • 120,166
  • 34
  • 186
  • 219
1
f = open('file1.txt').readlines()

open('file1.txt', 'w').writelines(lines[4:])

This code snippet will delete first four line from fie name "file1.txt"

rahul kumar
  • 99
  • 1
  • 2
  • should be f = open('file1.txt').readlines() open('file1.txt', 'w').writelines(f[4:]) instead – quarkz May 19 '22 at 06:52
-4

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