1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.