如何在Python中读取和删除文件中的前n行-优雅的解决方案 [英] How to read and delete first n lines from file in Python - Elegant Solution

查看:984
本文介绍了如何在Python中读取和删除文件中的前n行-优雅的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的文件〜1MB,我希望能够读取前N行,将它们保存到列表( newlist )中以备后用,然后删除它们.

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.

我能够这样做:

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")

这篇关于如何在Python中读取和删除文件中的前n行-优雅的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆