fileinput module doesn't work to spec?

Carel Fellinger cfelling at iae.nl
Wed Oct 25 19:13:37 EDT 2000


Dale Strickland-Clark <dale at out-think.nospamco.uk> wrote:
> Thanks to all who replied.

> I understand how the redirection works now but what happens if you
> need to write out the last line read? Is the redirection still around?

Ofcourse it is, at least as long as you do the writing within the body of
that loop over all the lines of all the input files.

You see, what happens is something like this:

the for statement asks a line object from the sequence object created
by "fileinput.input(...)". That sequence object is actually a class
instance that happens to have the special "__get_item__" method. And it
is precisely this "__get_item__" method that is used by the for loop
mechanism to iterate through the sequence (of input lines/files). And it
will keep up this good work until an "IndexError" exception is raised.

All that that "__get_item__" method does is cleverly-read a line, and if
that line is empty (and it is in the end) raise the "IndexError" exception.

The real work is done it the clever-reading part. The first time around
a copy of the first file is opened, output is redirected to the original
file, and the first line is cleverly-read. And here lies much of the
beauty of the readline package, the reading is realy clever. If it hits
the end of the current file, it simply closes the current input and output
files, undoes the redirection and calls itself recursively. So it opens
a copy of the next file, redirect output to that original file and does
its cleverly-reading again and again until it succedes or it hits the end
of the last file. Only in the latter case will it return an empty line.

So if in the for loop you just read the last line of the last file, you
still have all of the body of that loop to deal with this last line.
Then the for loop mechanisme tries to read the next line, this doesn't
excist, so the clever-reading closes the current files and tries to open
the next file. There is no next file so it returns an empty line, this
triggers the "IndexError" exception in the "__get_item__" method, and
this tells the for loop mechanism that the loop is actually over.

Sorry for this long-winding explanation, hope it gives better insight
in the workings of this marvelous language instead of confusing you:)
-- 
groetjes, carel



More information about the Python-list mailing list