[Tutor] A quick question

dman dsh8290@rit.edu
Fri, 9 Nov 2001 14:16:16 -0500


On Fri, Nov 09, 2001 at 11:09:59AM -0800, Danny Yoo wrote:
| On Sat, 10 Nov 2001, Edy Lie wrote:
| 
| >    I was thinking to change the following codes to python but aint
| > sure how should i approach it.
| 
| Hi Edy!  Sure; let's take a look.
| 
| >   open (SEARCH, "$file") or die switch();
| >   while ($line = <SEARCH>) {
| >   ...
| > }
| 
| This while loop in Perl can be written in Python like this:
| 
| ###
| for line in f.readlines():
|     ....
| ###
| 
| This is not exactly equivalent though, since this translation tries to
| suck the whole file at once.  This might be a good thing if the file is
| small, but if the file is fairly large, you'll probably want to eat it a
| line at a time.
| 
| 
| In that case, we can rewrite it like this:
| 
| ###
| while 1:
|     line = f.readline()
|     if not line: break
|     ...
| ###

If you have python 2.0 or newer, I prefer

for line in f.xreadlines() :
    ...

to lazily iterate over all the lines in a file.

-D