If you truly wish to kill yourself trying to make it as efficient memory as
possible, then you can follow this example. (This is more like what I would
write in C).
The getrandomline function picks a random byte between the beginning and the
end of the file, then backs up until the beginning of the line and uses
readline to return the whole line.
I tested it :-)


#############################################
from os import stat
from random import randint

def getrandomline(f, length):
    pos = randint(0,length)
    f.seek(pos)
    while f.read(1)!='\n':
        try:
          f.seek(-2,1)
        except IOError:           # This is to catch seeking before the
beginning of the file
          f.seek(0)
    return f.readline()

f = file("quotes.txt","rb")
sizeoffile = stat("quotes.txt")[6]

while (1):
  print getrandomline(f, sizeoffile),

f.close()
###################################

This holds at 3,688 K mem usage, whereas with the same file (100,000 lines),
using readlines gives me 47,724 K.  Big difference. Maybe not important to
you, but I'm strange.

Hope this helps.

JS

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to