pythonian way

Ray Loyzaga ray at
Sun Feb 27 04:21:46 EST 2000

Alan Daniels wrote:
> On Fri, 25 Feb 2000 08:33:15 +0100, the infinitely wise Milos Prudek
> (prudek at spoke forth to us, saying...
> [snip...]
> >The following excerpt works. It reads lines from config file. But I
> >would like to ask if it is 'right' in the Pythonian way.
> >A=[]
> >Line=H.readline()
> >while Line<>'':
> >       if Line<>'' and Line<>'\n':
> >               A.append(Line)
> >       Line=H.readline()
> I myself would use:
> A = []
> for Line in H.readlines():
>     if Line not in ("", "\n"):
>         A.append(Line)

the test for "" is redundant for both implementations.
For the first the "while" test catches this, and for the second
the readlines() routine terminates on "", i.e. end of file, and
hence does not return a list with "" components.
I personally don't see the point to spotting '\n', if a config
file is being scanned, you either can live with empty lines, or
you want to nuke "empty" lines, i.e. lines where string.strip would
return "".
If the latter is the case then:
import sys
import string

H = sys.stdin
for i in H.readlines():	
        if string.strip(i):	# works for the unreliable family of OS's from MS

or if speed is to be sought in preference to clarity:
import sys
import string


A=filter(string.split, H.readlines())

More information about the Python-list mailing list