[Tutor] Re: [Tutor]Reading and Writing (No Arithmetic?)

Paul Sidorsky paulsid@shaw.ca
Fri, 18 Jan 2002 20:01:41 -0700


tbrauch@tbrauch.com wrote:

> newQuote = quotes[random.randrange(0,quotes.len())]

This can be shortened to:

newQuote = random.choice(quotes)

> But, how could I get a random line if there are thousand of lines in the
> data file without bogging down the computer?

I think there are a couple of libraries around for that kind of thing. 
However, if you want to do it yourself (which is usually more fun :-)),
there are two options that shouldn't be too hard to implement. 

One is to move to a fixed-length quote string.  Then when you want to
choose, get the file size (s), divide it by the fixed length (l), then
pick a number (n) from 0 to (s/l)-1, seek n*l bytes into the file, and
read your quote.  The bad news is you waste space and also lose some
ease of maintainability of the quotes file.

Another idea is to build an index of some kind.  A simple one would have
the number of quotes first, followed by the offsets of each of the
quotes.  Then you can read in the number of quotes, pick your random
number, find its offset in the index, seek to it, and read to the
newline.  This keeps the maintainability and doesn't use as much extra
space, but of course any time you change the quotes file you have to
remember to rebuild the index.

Hope that helps.  Admittedly these are very C-like approaches; there
might be something nicer that Python can do that I've missed.  I haven't
worked with binary files in Python much.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/