-3

Python’s for statement iterates over the items of any sequence (a list or a string).

But where does the sequence come from in below code?

file=open('filename.txt','r')
for line in file:
    print line

Is this related to the __iter__() method?

Just some quote:

https://docs.python.org/3/glossary.html#term-iterable

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
smwikipedia
  • 61,609
  • 92
  • 309
  • 482
  • The quote you included *answers your question* already. `iter()` is called on the file object. The file object returns `self` for that. What is not clear here? – Martijn Pieters May 19 '14 at 15:08

1 Answers1

1

Python's for statement iterates over the items of any iterable object, not just sequences:

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object

Iterables are objects that either have an __iter__ method or a __getitem__ method.

file objects implement an __iter__ method; they also are iterator objects, in that they have a __next__ method (Python 3) or next method (Python 2), so all the __iter__ method of a file object has to do is return self.

For Python 3, also see the io.IOBase documentation:

IOBase (and its subclasses) supports the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343