[Tutor] beginner question

Peter Otten __peter__ at web.de
Tue Nov 1 17:06:22 CET 2011


Steve Willoughby wrote:

> On 01-Nov-11 08:34, Mayo Adams wrote:
>> When writing a simple for loop like so:
>>
>>       for x in f
>>
>> where f is the name of a file object, how does Python "know" to interpret
>> the variable x as a line of text, rather than,say, an individual
>> character in the file? Does it automatically
>> treat text files as sequences of lines?
> 
> Every object defines what its behavior will be when asked to do
> something.  In this case, file objects know that they are capable of
> iterating over a list of their contents by being used in a "for x in f"
> loop construct.  The file object knows to respond to that by yielding up
> a line from the file for every iteration.
> 
> You could, theoretically, write a variation of the file object class
> which iterated over characters, or logical blocks (records of some sort)
> within files, and so forth.
 
Here's a simple example of a class derived from file that iterates over 
characters (bytes) instead of lines.

Standard file:

>>> for line in open("tmp.txt"):
...     print repr(line)
...
'this\n'
'is but an\n'
'example\n'

Modified file class:

>>> class MyFile(file):
...     def next(self):
...             c = self.read(1)
...             if not c:
...                     raise StopIteration
...             return c
...
>>> for c in MyFile("tmp.txt"):
...     print repr(c)
...
't'
'h'
'i'
's'
'\n'
'i'
's'
' '
'b'
'u'
't'
' '
'a'
'n'
'\n'
'e'
'x'
'a'
'm'
'p'
'l'
'e'
'\n'




More information about the Tutor mailing list