Python - 一次从文件中读取1000行

Ton*_*ous 6 python python-2.7

我已经检查了这个,这个这个.

第三个链接似乎有答案,但它没有完成这项工作.

我无法找到将整个文件带到主内存的解决方案,因为我将使用的文件非常大.所以我决定使用islice第3个链接中显示的内容.前2个链接无关紧要,因为它们仅用于2行或读取1000个字符.而我需要1000行. for now N is 1000

我的文件包含100万行:

样品:

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
Run Code Online (Sandbox Code Playgroud)

因此,如果我一次读取1000行,我应该经历一段while 1000时间,但是当我打印p以检查我已经完成了多少次时,它并没有停留在a 1000.它19038838运行我的程序1400几秒钟后达成了!

码:

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

Shi*_*ndi 5

正如@ Ev.kounis所说,你的while循环似乎不能正常工作.

我建议像以下一样去获取数据块的yield函数:

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)]
Run Code Online (Sandbox Code Playgroud)

  • 不,它只会重复for循环中的步骤.收益率可以解释为"返回此输入并在被要求时完全返回".查看生成器的doc:https://docs.python.org/3/howto/functional.html#generators (2认同)