Python 如何在不复制和切片整个文件的情况下删除文件的第一行?
我有一个文件如下所示:Python 如何在不复制和切片整个文件的情况下删除文件的第一行?,python,file,file-io,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/wik
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)
如何删除文件的第一行(即用第二行替换第一行),而不将整个文件加载到内存中并对其进行切片?(我的内存有限。)重新打开并跳过第一行:
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
另一个选项是使用模块:
这太棒了。这么简单。
import fileinput
for line in fileinput.input('file.txt', inplace=1):
if fileinput.lineno() > 1:
print line[:-1]
fileinput.close()