[Tutor] Print record x in a file

David Holland davholla2002 at yahoo.co.uk
Sat Jan 22 22:58:01 CET 2005


This will get a random record 
I hope you do not think the comments are patronising
but you did say you are new so I did not want to give
naked code.

import random
#the above gives the program the ability to get a
#pseudo random number
file = open('test.rantxt')
listcontents = file.readlines()
#gives you the file as a list of records or it did on
#(assuming each line is a record)
file.close()
lenoflist = len(listcontents)-1
#find the length of the list and take one of because
computers count from 0
x = random.randrange(0,lenoflist)
print listcontents[x]


	
	
		
___________________________________________________________ 
ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com


More information about the Tutor mailing list