mrmmickle1
mrmmickle1

Reputation: 15

Python Open() and File Handles?

I'm new to Python and I have read a file into memory. I then do a simple loop to see what the contents of the file are....

Then I try to perform another action on the file and it appears it has disappeared or left memory?

Can someone please explain what's going on and how I can store a file in memory to query it?

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

Upvotes: 0

Views: 628

Answers (1)

chepner
chepner

Reputation: 531035

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 second for 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.

>>> 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

Note the difference between the TextIOWrapper object returned by open:

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

and a list, which is not its own iterator.

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

Each call to iter(x) returns a different iterator for the same list x.

Upvotes: 1

Related Questions