假设open() 一次读取 2 个字母。 (实际值为io.DEFAULT_BUFFER_SIZE)
f=open('test.txt')
您已经创建了一个文件对象 _io.TextIOWrapper,它过于简单化了,就像 [{read from 0 to io.DEFAULT_BUFFER_SIZE of test.txt}, ...}
file=iter(f)
您已经创建了 _io.TextIOWrapper 的迭代器,其数据如下:[{read from 0 to 1}, ... {read from n-1 to n}]
next(file)
next() 浏览了file 的第一项,阅读并打印。
让我们从一个例子中学习。
正常阅读
test.txt
what a beautiful day
我们将打开文件,iter() 和 list() 打开并遍历所有文件并创建一个列表。
In [1]: f = open('test.txt')
In [2]: list(iter(f))
Out[2]: ['what a beautiful day']
正如预期的那样。
open() 之后的文件更改
In [1]: f = open('test.txt')
我们已经打开了文件。
我们现在将 hello open() 附加到 test.txt。
test.txt
what a beautiful day
hello open()
然后是 iter() 和 list() 它。
In [2]: list(iter(f))
Out[2]: ['what a beautiful day\n', '\n', 'hello open()']
可以看到更改的内容。我们可以看到open()实际上并没有读取文件。
iter() 之后的文件更改
In [1]: f = open('test.txt')
In [2]: i = iter(f)
我们已经打开了文件和iter()d。
我们现在将追加hello iter()
test.txt
what a beautiful day
hello open()
hello iter()
然后列出()它。
In [3]: list(i)
Out[3]: ['what a beautiful day\n', '\n', 'hello open()\n', '\n', 'hello iter()']
可以看到更改的内容。我们还可以看到iter()实际上并没有读取文件。