Python Open() 和文件句柄?

Python Open() and File Handles?

我是 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)

open 编辑的对象 return 作为它自己的迭代器。当您遍历其内容时,文件指针将保留在文件末尾。这意味着第二个 for 循环 在最后开始 ,而不是得到一个从开头开始的 "fresh" 迭代器。

要再次迭代,使用seek方法return到文件开头。

>>> fh = open("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
<b>>>> fh.seek(0)
0</b>
>>> 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

请注意 open 编辑的 TextIOWrapper 对象 return 之间的区别:

>>> type(fh)
<class '_io.TextIOWrapper'>
>>> type(iter(fh))
<class '_io.TextIOWrapper'>
>>> fh is iter(fh)
True

和一个列表,它不是它自己的迭代器。

>>> x = [1,2,3]
>>> type(x)
<class 'list'>
>>> type(iter(x))
<class 'list_iterator'>
>>> x is iter(x)
False

每次调用 iter(x) return 都是针对同一列表的 不同 迭代器 x