如何在不复制和切片整个文件的情况下删除文件的第一行?

时间:2014-10-26 20:24:22

标签: python file file-io

我有一个看起来像这样的文件:

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)

如何删除文件的第一行(这意味着用第二行替换第一行)而不将整个文件加载到内存中并将其切片? (我的记忆力有限。)

2 个答案:

答案 0 :(得分:2)

重新开启并跳过第一行:

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

答案 1 :(得分:0)

另一个选择是使用fileinput模块:

import fileinput

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