基本上不能从文件开头删除东西,必须写入新文件。
我觉得pythonic方式看起来是这样的:
# getaiteratoroverthelinesinthefile :
withopen(input.txt,) rt ) ) as lines:
# while the line is not empty drop it
for line in lines:
if not line.strip () :
布雷克
# nowlinesisatthepointafterthefirstparagraph
# so write out everything from here
withopen(output.txt,) wt ) ) as out:
out.writelines(lines )或更低版本是简单的版本,旧版本的Python没有with。
lines=open('input.txt ',' rt ' ) )。
for line in lines:
if not line.strip () :
布雷克
open('output.txt ',' wt ' ).writelines(lines )和非常简单的版本,只需在空行中拆分文件。
# first,read everything from the old file
text=open('input.txt ',' rt ' ).read ) )
# splititatthefirstemptyline ('nn ' ) )。
first,rest=text.split('nn ',1 ) )。
# make a new文件and write the rest
open(output.txt ),wt ).write(rest )请注意,这可能非常脆弱。 例如,Windows通常将rn用作单个换行符,因此空行将更改为rnrn。 但是,这可能没有问题,因为我们知道文件格式通常只使用一种换行符。