[Tutor] Print record x in a file

David Holland davholla2002 at yahoo.co.uk
Sun Jan 23 22:55:27 CET 2005


 --- tutor-request at python.org wrote: 
> Send Tutor mailing list submissions to
>  tutor at python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
>  http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
>  tutor-request at python.org
> 
> You can reach the person managing the list at
>  tutor-owner at python.org
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. Re: Print record x in a file (Kent Johnson)
>    2. How would python messure up in performance?
> (Kevin)
>    3. Re: How would python messure up in
> performance? (Max Noel)
>    4. Re: Print record x in a file (David Holland)
>    5. on the way to find pi (Ali Polatel)
>    6. Re: on the way to find pi (Max Noel)
>    7. Re: on the way to find pi (Orri Ganel)
> 
> 
>
----------------------------------------------------------------------
> 
> Message: 1
> Date: Sun, 23 Jan 2005 07:46:08 -0500
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] Print record x in a file
> Cc: tutor python <tutor at python.org>
> Message-ID: <41F39C90.60602 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1;
> format=flowed
> 
>   Since len(listcontents) is one greater than the
> largest valid index of listcontents, the correct 
> use of randrange() for this problem is
>    x = random.randrange(0, len(listcontents))
> 


Kent,

I know that you know far more about python than me but
is that right ?
I created file with 4 records and this code did print
them all randomly:-

import random
i = 0
while i < 10:
    file = open('filename')
    listcontents = file.readlines()
    file.close()
    lenoflist = len(listcontents)-1
    x = random.randrange(0,lenoflist)
    print listcontents[x], i
    i = i +1


While although this code below does work many times
nothing is printed out.
import random
i = 0
while i < 10:
    file = open('test.rantxt')
    listcontents = file.readlines()
    file.close()
    lenoflist = len(listcontents)#-1
    x = random.randrange(0,lenoflist)
    print listcontents[x], i
    i = i +1


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


More information about the Tutor mailing list