我是Python的新手,我已将文件读入内存。然后,我做一个简单的循环来查看文件的内容是...。
然后,我尝试对文件执行其他操作,并且看起来文件已消失或内存不足?
有人可以解释发生了什么,如何将文件存储在内存中以进行查询吗?
>>> fh = open('C:/Python/romeo.txt')
>>> for line in fh:
... print(line.rstrip())
...
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
>>> for line in fh:
... print(line)
The object returned by
open
acts as its own iterator. When you iterate over its contents, the file pointer remains at the end of the file. That means the secondfor
loop starts at the end, rather than getting a "fresh" iterator that starts at the beginning.To iterate again, use the
seek
method to return to the start of the file.Note the difference between the
TextIOWrapper
object returned byopen
:还有一个列表,它不是它自己的迭代器。
Each call to
iter(x)
returns a different iterator for the same listx
.