Reputation: 499
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
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
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
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
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