def manual_iter(): with open('/etc/passwd') as f: try: while True: line = next(f) print(line, end='') except StopIteration: pass
or
with open('/etc/passwd') as f: while True: line = next(f, None) if line is None: break print(line, end='')
下面的交互示例向我们演示了迭代期间所发生的基本细节:
>>> items = [1, 2, 3] >>> # Get the iterator >>> it = iter(items) # Invokes items.__iter__() >>> # Run the iterator >>> next(it) # Invokes it.__next__() 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>