[Tutor] reading random line from a file

bhaaluu bhaaluu at gmail.com
Thu Jul 19 17:40:02 CEST 2007


Greetings,
Thanks for including the complete source code!
It really helps to have something that works to look at.
I modified an earlier version of this to run on my
computer (GNU/Linux; Python 2.4.3).
The os.module() stuff is new for me, so I played
around with it... here's my modified file just in case
another beginner is interested:

#!/usr/bin/env python
"""
2007-07-19
Modified snippet from Tutor mailing list.
Example of checking to see if a file exists, using 'os.path()'
Examples of using 'os.system()' with wget and mv commmands.
Lookup: enumerate(), random.randint()
This is obviously NOT cross-platform. Works on GNU/Linux.
b h a a l u u at g m a i l dot c o m
"""
import os
import random

def randline():
 text = 'list_classifiers'
 if not os.path.exists(text):
   os.system('wget
http://cheeseshop.python.org/pypi?%3Aaction=list_classifiers ')
   os.system('mv pypi\?\:action\=list_classifiers list_classifiers')
 f = file(text, 'rb')
 for i,j in enumerate(f):
    if random.randint(0,i) == i:
       line = j
 f.close()
 return line

while True:
 print "\n", randline()
 answer = raw_input("Another line? [y/n]: ")
 if answer == 'n':
   break

Happy Programming!
--
bhaaluu at gmail dot com


More information about the Tutor mailing list