Reputation: 11
I am new to python, learning data structures now. and i got stuck with files. I felt this very unusual, can anyone help me with a good reason why this is happening. here is my code.
(this is the link for text file http://www.pythonlearn.com/code/romeo.txt)
fh = open('romeo.txt')
for line in fh:
print line
Output:
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
Here I am not able to print the lines using fh
for the second time, it outputs nothing.
Upvotes: 1
Views: 49
Reputation: 4076
That's because iterating through the lines moves the current position.
One of the things you could do is move the position back to the start:
fh.seek(0)
You may also find this Python file reading tutorial useful: http://www.diveintopython3.net/files.html
Upvotes: 1