Python Open()和文件句柄?

问题描述 投票:0回答:1

我是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)
python file read-write
1个回答
1
投票

返回的对象是 open 作为它自己的迭代器。当你迭代它的内容时,文件指针会留在文件的最后。这意味着第二个 for开始 而不是得到一个从头开始的 "新 "迭代器。

要再次迭代,使用 seek 方法来返回到文件的开始。

>>> 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
>>> fh.seek(0)
0
>>> 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

请注意 TextIOWrapper 返回的对象 open:

>>> 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) 返回一个 不同 迭代器 x.

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