python修改可变迭代器

问题描述 投票:4回答:2

代码如下:

f=open('test.txt')
file=iter(f)

当我做

next(file)

它将逐行打印文件。但是当我修改test.txt文件并保存它时,下一个(文件)仍然打印了原始文件内容。

迭代器是否将完整文件存储在内存中?如果不是为什么文件的内容没有得到更新?

python iterator generator
2个回答
2
投票

不,作为迭代器,file对象只在内存中存储一​​个预见缓冲区,而不是完整的文件。这使得它对大文件有效。

由于存在此前瞻缓冲区,因此对文件所做的更改不会反映到next方法中。但是,您可以使用seek方法清除此缓冲区,以便下次调用next方法将返回更新的内容:

f.seek(f.tell()) # seek the current position only to clear the look-ahead buffer
print(next(f)) # prints the updated next line from the current position

1
投票

让我们假设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的第一项,阅读并打印出来。

Let's learn from an example.

正常阅读

的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()实际上并没有读取该文件。

© www.soinside.com 2019 - 2024. All rights reserved.