2017-01-30 100 views
6

我已经选择thisthisthisPython - 一次从文件读取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行,我应该通过while1000倍,但是当我打印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 

我在做什么错?

+1

了'F'可能是不消耗,所以你最终会每次读取相同,相同的1000线。这永远不会终止。你必须使用替代配方'islice'('itertools.islice(迭代器,启动,停止[,步])'这一个,而不是'itertools.islice(迭代器,停止)'这个) –

回答

5

作为@ Ev.kounis说你的while循环似乎不能正常工作。

我会建议去为数据块的产量在功能这样的时刻:

def get_line(): 
    with open('your file') as file: 
     for i in file: 
      yield i 

lines_required = 1000 
gen = get_line() 
chunk = [next(gen) for i in range(lines_required)] 
+0

但是那会不会尝试为每行打开相同的文件'1M'次?它会减慢程序,不是吗? –

+2

不,它只会重复for循环中的步骤。产量可以解释为“返回此输入,当被问及回来正是这里。”看看DOC发电机:https://docs.python.org/3/howto/functional.html#generators – MKesper

+0

@MKesper 又如何,如果该文件是在这样我就可以停止迭代和阅读? '如果不是chunk:break'不起作用。有任何想法吗 ? –