Sam
Sam

Reputation: 499

How come i need to make another file handle to read the same file again?

I was playing around files with python, so i wrote this:

 ifh=open('2.txt','r')  
   for line in ifh:  
     print(line,end="")
 print("Done")
 #ifh=open('2.txt','r')
    for line in ifh:
      print(line)

The second loop does print the file only if i uncomment the second file handle.
Why is that?
Shouldn't it work without the second one?

Upvotes: 2

Views: 284

Answers (5)

NPE
NPE

Reputation: 500207

It's because after the first loop is finished, ifh's current position is at the end of the file. At that point, there is no more data to read.

To read the data again, you need to use ifh.seek(0) to move back to the beginning of the file.

Upvotes: 1

Oni1
Oni1

Reputation: 1505

You can also make a closed loop ahead of the for-loop.

while True:
    for line in ifh:
        print(line,end=" ")

Upvotes: 0

Zygimantas Gatelis
Zygimantas Gatelis

Reputation: 2033

Do: ifh.seek(0) before second loop.

Its because you read all lines from the file and seek method goes to the first byte of file, and you can read it again.

Upvotes: 0

Anthon
Anthon

Reputation: 76588

You are at the end of the file when you print Done. you can do a ifh.seek(0) to get to the beginning again.

Upvotes: 0

squiguy
squiguy

Reputation: 33360

Because you need to seek back to the beginning of the file using this:

ifh.seek(0)

When you open the file again for reading, it resets the file's current position to the beginning.

Upvotes: 1

Related Questions