[英]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.