[Tutor] Readlines

Alan Gauld alan.gauld@blueyonder.co.uk
Sun Jun 22 03:40:01 2003


> you folks think. Take the code below. I notice that Read() is
> apparently incredibly slow! 

Reading from a file is slower than reading from memory so don't 
expect reading a file character by character to be fast.

> fhand=open(filepath,'r')
> 
> while c!='':
>     while z!='\n':
>         z=fhand.read(1)
>         print z,
>     ln=ln+1
>     c=z

You could replace this with:

ln = 0
while 1:
     line = f.readline()
     if not line: break
     print line
     ln += 1
     if ln % 100 == 0: print ln

Note readline singular.

Even easier should be

for line in f.xreadlines():
    print line

Note xreadlines() not readlines...

Alan G.