user4183746
user4183746

Reputation:

How do I remove the first line of a file without copying and slicing the whole file?

I have a file that looks like this:

http://en.wikipedia.org/wiki/Siege_of_Amirli
http://en.wikipedia.org/wiki/Patia
http://en.wikipedia.org/wiki/2011_Coastal_Carolina_Chanticleers_football_team
http://en.wikipedia.org/wiki/Lezayre_railway_station
http://en.wikipedia.org/wiki/Secretariat_for_Economy_and_Finance_(Macau)

How do I remove the first line of the file (which means replacing the first line with the second one) without loading the whole file into memory and slicing it? (I have only limited memory.)

Upvotes: 0

Views: 106

Answers (2)

dreyescat
dreyescat

Reputation: 13818

Another option is using the fileinput module:

import fileinput

for line in fileinput.input('file.txt', inplace=1):
    if fileinput.lineno() > 1:
        print line[:-1]
fileinput.close()

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

Reopen and skip first line:

with open(infile) as f:
    next(f) # skip first line
    with open(infile,"w") as f1:
        for line in f:
            f1.write(line) # write from second line

Upvotes: 2

Related Questions