我已经选择this,this和this。Python - 一次从文件读取1000行
第三个链接似乎有答案,但它没有做这项工作。
我不能有一个解决方案将整个文件带到主内存中,因为我将要使用的文件将非常大。所以我决定使用islice
,如第三个链接所示。前2个链接是不相关的,因为他们只用了2行或读了1000个字符。而我需要1000行。for now N is 1000
我的文件包含百万线:
样品:
1 1 1
1 2 1
1 3 1
1 4 1
1 5 1
1 6 1
1 7 1
1 8 1
1 9 1
1 10 1
所以,如果我一次读取1000行,我应该通过while
1000
倍,但是当我打印p
来检查我已经进行了多少次,它并不停止在1000
。它在运行我的程序1400
秒后达到19038838
!
CODE:
def _parse(pathToFile, N, alg):
p = 1
with open(pathToFile) as f:
while True:
myList = []
next_N_lines = islice(f, N)
if not next_N_lines:
break
for line in next_N_lines:
s = line.split()
x, y, w = [int(v) for v in s]
obj = CoresetPoint(x, y)
Wobj = CoresetWeightedPoint(obj, w)
myList.append(Wobj)
a = CoresetPoints(myList)
client.compressPoints(a) // This line is not the problem
print(p)
p = p+1
c = client.getTotalCoreset()
return c
我在做什么错?
了'F'可能是不消耗,所以你最终会每次读取相同,相同的1000线。这永远不会终止。你必须使用替代配方'islice'('itertools.islice(迭代器,启动,停止[,步])'这一个,而不是'itertools.islice(迭代器,停止)'这个) –