[Tutor] reading random line from a file

Tiger12506 keridee at jayco.net
Mon Jul 16 17:48:34 CEST 2007


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



More information about the Tutor mailing list