如何在文件中使用for循环在Python中工作?

0x4*_*141 3 python python-2.7

我有这段代码

f = open('textfile.txt', 'r')
for line in f:
    print line
Run Code Online (Sandbox Code Playgroud)

我只想说textfile.txt是这样的

1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

这是如何运作的?它是如何知道文件中的位置的?我知道它是一遍又一遍地打印,但为什么不一遍又一遍地打印整个文件.我不知道f是一个范围.我还假设它知道停在EOF?

Cha*_*nga 5

调用open()返回文件对象 - 即f文件对象.文件对象是它们自己的迭代器,实现了该next()方法,允许它们for按照你的例子在循环中使用.是的,迭代器实现知道停在EOF.在file.next()方法细节下查看此处的描述:http: //docs.python.org/2/library/stdtypes.html#bltin-file-objects