繁体   English   中英

python修改可变迭代器

[英]python modify mutable iterator

代码如下:

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

当我做

next(file)

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

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

不,作为迭代器, 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

我们假设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()实际上并没有读取文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM