[Tutor] Unusual behavior in readline

Alan Gauld alan.gauld at freenet.co.uk
Tue Aug 8 23:12:39 CEST 2006


>I don't understand why readline is producing such unusual behavior.
> I don't remember it working like this previously. The docs say it is
> supposed to read a line at a time.

It does.

> def ProcessFile(self, Inputfile, Outputfile=None):
>
>        try:
>            fh=open(Inputfile,"r")
>        except IOError:
>            print"\nError ocurred opening %s for input\n" % Inputfile
>        else:
>            FixedEntry = []
>            Entry = ""

You don't need to initialise Entry, the for loop does that for you.


>            for Entry in fh.readline():

readline returns a string and the for loop iterates over it.
You need readl;ines to return all of the strings in the file.
Or nowadays just use

               for Entry in fh:

>                print"Entry = %s" % Entry

BTW Why not just put all this stuff in the body of the try?
Thats what try/except is for, to stop cluttering up the code with
error handling sections and move that to the end out of the way....
You should very rarely need an else clause when using try/except.

> Readline is supposed to read an entire line on each call,
> yet it is only reading one character.

No, it is reading a line, you are then iterating over that line
one character at a time.

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list