[Tutor] reading random line from a file

Nathan Coulter com.gmail.kyleaschmitt at pooryorick.com
Wed Jul 18 23:15:41 CEST 2007


>  -------Original Message-------
>  From: Tiger12506 <keridee at jayco.net>

>  Yuck. Talk about a one shot function! Of course it only reads through the
>  file once! You only call the function once. Put a second print randline(f)
>  at the bottom of your script and see what happens :-)
>  
>  JS
>  

*sigh*

#!/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')

def randline(f):
    for i,j in enumerate(file(f, 'rb')):
        if random.randint(0,i) == i:
            line = j
    return line

print randline(text)
print randline(text)
print randline(text)

-- 
Yorick


More information about the Tutor mailing list