【发布时间】: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