[Tutor] reading random line from a file

Poor Yorick org.python.tutor at pooryorick.com
Wed Jul 18 15:04:05 CEST 2007


>  -------Original Message-------
>  From: Kent Johnson <kent37 at tds.net>
>  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


More information about the Tutor mailing list