python文件删除前几行,如何在Python中从文件读取和删除前n行-优雅的解决方案

I have a pretty big file ~ 1MB in size and I would like to be able to read first N lines, save them into a list (newlist) for later use, and then delete them.

I am able to do that like this:

import os

n = 3 #the number of line to be read and deleted

with open("bigFile.txt") as f:

mylist = f.read().splitlines()

newlist = mylist[:n]

os.remove("bigFile.txt")

thefile = open('bigFile.txt', 'w')

del mylist[:n]

for item in mylist:

thefile.write("%s\n" % item)

I know this doesn't look good in terms of efficiency and this is why I need something better but after searching for different solutions I was stuck with this one.

解决方案

A file is it's own iterator.

n = 3

nfirstlines = []

with open("bigFile.txt") as f, open("bigfiletmp.txt", "w") as out:

for x in xrange(n):

nfirstlines.append(next(f))

for line in f:

out.write(line)

# NB : it seems that `os.rename()` complains on some systems

# if the destination file already exists.

os.remove("bigfile.txt")

os.rename("bigfiletmp.txt", "bigfile.txt")

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值