【问题标题】:How to read and delete first n lines from file in Python - Elegant Solution[2]如何在 Python 中读取和删除文件的前 n 行 - 优雅的解决方案 [2]
【发布时间】:2017-07-26 23:22:23
【问题描述】:

原帖在这里:How to read and delete first n lines from file in Python - Elegant Solution

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

我原来的代码是:

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”错误

【问题讨论】:

  • 作为提示...f.read().splitlines() 消耗整个文件...
  • 您的文件已用尽。你需要回到文件的开头fo.seek(0, 0)

标签: python python-2.7 list


【解决方案1】:

在您的示例代码中,您正在阅读整个文件以找到第一行 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)

【讨论】:

    【解决方案2】:

    我会按照以下方式进行:

    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)
    

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多