[Tutor] reading random line from a file

Kent Johnson kent37 at tds.net
Wed Jul 18 12:19:38 CEST 2007


Tiger12506 wrote:
> 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.

It probably doesn't matter, but this will pick longer lines more often 
than short ones.

> I tested it :-)

Hmm. What happens if you run it on a file with only one line? (see below)
> 
> 
> #############################################
> 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)

I think you need a break here to avoid an infinite loop.

Kent

>     return f.readline()
> 
> f = file("quotes.txt","rb")
> sizeoffile = stat("quotes.txt")[6]
> 
> while (1):
>   print getrandomline(f, sizeoffile),
> 
> f.close()
> ###################################


More information about the Tutor mailing list