> -------Original Message------- > From: Kent Johnson <[EMAIL PROTECTED]> > Subject: Re: [Tutor] reading random line from a file > Sent: 2007-07-18 10:19 > [SNIP] > > It probably doesn't matter, but this will pick longer lines more often > than short ones. >
This method only keeps one line in memory, only reads through the file once, and does not favor lines based on any characteristic of the line. It's probably fast enough to not even bother keeping an index around: #!/bin/env python import os import random text = 'shaks12.txt' if not os.path.exists(text): os.system('wget http://www.gutenberg.org/dirs/etext94/shaks12.txt') f = file(text, 'rb') def randline(f): for i,j in enumerate(f): if random.randint(0,i) == i: line = j return line print randline(f) --- Yorick _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor