pythonian way

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Fri Feb 25 03:10:12 EST 2000


Milos Prudek wrote in comp.lang.python:
> The following excerpt works. It reads lines from config file. But I
> would like to ask if it is 'right' in the Pythonian way. Since I'm just
> beginning in Python I do not want to twist Python into 'my' way of
> thinking. 
> 
> There is no eof() function for high level readline(), so I use '' to
> discover end of file.
> 
> A=[]
> Line=H.readline()
> while Line<>'':
> 	if Line<>'' and Line<>'\n':
> 		A.append(Line)
> 	Line=H.readline()

Your version skips empty lines. If that's not essential, you can just do:
A = H.readlines()

Maybe the fastest solution is using readlines() and filter() for large files,
I don't know. It's not very readable...

A = filter(lambda x: len(x) > 1, H.readlines())

The lambda constructs a function that checks if a string is longer than 1,
filter uses that to see which of the lines to keep.

Otherwise it's just a matter of style... I would maybe write

A = []
while 1:
    line = H.readline()
	if not line:
	    break
	if line != '\n':
	    A.append(line)


-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
  9:04am  up 93 days, 15:09,  7 users,  load average: 0.13, 0.14, 0.16



More information about the Python-list mailing list