读取文本文件的最佳方式(如下):
>>> for line in open('log.txt'):
... print(line.upper())
...
SPAM
1 2 3
G O O D !
手动迭代:iter和next
>>> f = open('log.txt')
>>> f.__next__()
'spam\n'
>>> f.__next__()
'1 2 3\n'
>>> f.__next__()
'\n'
>>> f.__next__()
'g o o d !\n'
>>> f.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
>>> f = open('log.txt')
>>> next(f)
'spam\n'
>>> next(f)
'1 2 3\n'
>>> next(f)
'\n'
>>> next(f)
'g o o d !\n'
>>> next(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
文件对象就是自己的迭代器,列表以及很多其他的内置对象,不是自身的迭代器,因为他们支持多次打开迭代器。对这样的对象我们必须调用iter来启动迭代。
>>> f = open('log.txt')
>>> iter(f) is f
True
>>> f.__next__()
'spam\n'
>>>
>>> L = [1,2,3]
>>> iter(L) is L
False
>>> L.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__next__'
>>> I = iter(L)
>>> I.__next__()
1
>>> next(I)
2
>>>
>>> for X in L:
... print(X**2,end= ' ')
...
1 4 9 >>>
>>> I = iter(L)
>>> while True:
... try:
... X = next(I)
... except StopIteration:
... break
... print(X**2,end=' ')
...
1 4 9 >>>