Jacob S. wrote:
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
Yes, but len returns counting from 1.
Anyway, you would have to add one to correct that anyway, wouldn't you?
If randrange is start <= x *<=* end, then you don't have to add one, you
just use the length.
If randrange is start<= x < end like __builtin__ range, you have to put
randrange(1,lenoflist+1)
x = random.randrange(0,lenoflist)
I would use randint because list indices need to be integers -- unless of
course I mistaken and
randrange returns an integer also. (But that would be repetitive to
have to
functions do the same thing)
print listcontents[x]
HTH,
Jacob
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
How about random.choice() ? Ie:
>>> print random.choice(f.readlines())
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor