3

I have this piece of code

f = open('textfile.txt', 'r')
for line in f:
    print line

lets just say the textfile.txt is something like this

1
2
3
4
5

How does this work? How does it know where it is in the file? I understand that it is printing over and over but why doesn't it just print the whole file over and over. I don't see how f is a range. I also assume it knows to stop at EOF?

2

1 Answer 1

5

Calling open() returns a file object - i.e. f is a file object. File objects are their own iterators, implementing the next() method, allowing them to be used in for loops as per your example. And yes, the iterator implementation knows to stop at EOF. Have a look at the description here, under the file.next() method details: http://docs.python.org/2/library/stdtypes.html#bltin-file-objects

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

2 Comments

Do C and other languages do this the same way? Do they have hidden functions being called when running a loop with fgets() or something similar. Or is this something only some languages do? It just seems weird to have stuff going on that isn't specified.
Different languages will have different implementations, but there are really only 2 basic principles at work here - treating a file as a collection of lines; and looping/iteration. Looping is generally a primitive operation in most languages, while iteration is a state-machine construct that simplifies looping over collections. Treating a file as a collection of lines is a nice conceptual construct that then ties in with iteration to give you the ability to for through a file.

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.