从读取文件中产生 islice

yielding islice from reading file

希望有人能帮助我理解以下内容。编写一个小程序来读取 K 行块中的 csv 文件。我已经看到了关于这个的其他堆栈问题,这不是我在这里要问的。我试图理解为什么一个程序终止而另一个程序从不终止。

此代码永远不会终止:

from __future__ import print_function
from itertools import islice
import time
import csv
def gen_csv1(input_file, chunk_size=50):
    try:
        with open(input_file) as in_file:
            csv_reader = csv.reader(in_file)
            while True:
                yield islice(csv_reader, chunk_size)
    except StopIteration:
        pass

gen1 = gen_csv1('./test100.csv')

for chunk in gen1:
    print(list(chunk))
    time.sleep(1)

虽然这很好用。唯一的区别是生成器 yield 之外的 islice

def gen_csv(input_file):
    try: 
        with open(input_file) as in_file:
            csv_reader = csv.reader(in_file)
            while True:
                yield next(csv_reader)
    except StopIteration:
        pass


gen = gen_csv('./test100.csv')
for chunk in gen:
    rows = islice(gen, 50)
    print(list(rows))
    time.sleep(1)

我很难过。非常感谢任何指导。这与其说是出于工作原因,不如说是出于好奇。

根据 the docs

[islice] works like a slice() on a list but returns an iterator.

切片空列表时,返回空列表:

In [118]: [][:3]
Out[118]: []

类似地,当您 islice 一个空迭代器时,将返回一个空迭代器。 相反,在空迭代器上调用 next 会引发 StopIteration:

In [98]: from itertools import islice
In [114]: reader = iter([])

In [115]: list(islice(reader, 3))
Out[115]: []

In [116]: next(reader)
StopIteration: 

由于 islice 从未引发 StopIteration 异常,因此代码的第一个版本永远不会终止。