如何在Python中从文件中读取和删除前n行 - 优雅解决方案[2]

时间:2017-03-06 22:17:54

标签: python python-2.7 list

最初发布在此处:How to read and delete first n lines from file in Python - Elegant Solution

我有一个相当大的文件~1MB大小,我希望能够读取前N行,将它们保存到列表中(新列表)供以后使用,然后删除它们。

我原来的代码是:

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)

基于已发布的Jean-François Fabre代码以及稍后已删除 here我可以运行以下代码:

import shutil

n = 3

with open("bigFile.txt") as f, open("bigFile2.txt", "w") as f2:
    for _ in range(n):
        next(f)
    f2.writelines(f)

这非常适合删除前n行和“更新”bigFile.txt,但是当我尝试将前n个值存储到列表中时,我可以稍后使用它们:

with open("bigFile.txt") as f, open("bigFile2.txt", "w") as f2:
    mylist = f.read().splitlines()
    newlist = mylist[:n]
    for _ in range(n):
        next(f)
    f2.writelines(f)

我收到“StopIteration”错误

2 个答案:

答案 0 :(得分:0)

在示例代码中,您正在阅读整个文件以查找第一行n行:

# this consumes the entire file
mylist = f.read().splitlines()

这使得后续代码无需读取任何内容。而只是做:

with open("bigFile.txt") as f, open("bigFile2.txt", "w") as f2:
    # read the first n lines into newlist
    newlist = [f.readline() for _ in range(n)]
    f2.writelines(f)

答案 1 :(得分:0)

我将按以下步骤进行:

n = 3
yourlist = []
with open("bigFile.txt") as f, open("bigFile2.txt", "w") as f2:
    i=0
    for line in f:
        i += 1
        if i<n:
            yourlist.append(line)
        else:
            f2.write(f)