Re: [users] Re: random lines
On Sun, Jul 01, 2001 at 06:12:49PM +0200, Martin F. Krafft wrote:
> > from random import *
> > from linecache import *
> > print getline('~/.muttrc',randrange(1,20))
>
> except that hardcodes the file length, does it not?
Yep, like I said it was a quickie example. Here's something that
wouldn't have the number of lines hard-coded:
--begin code--
from random import *
listfile = open('filename','r')
albumlist = listfile.readlines()
listfile.close()
print albumlist[randrange(0, len(albumlist))]
--end code--
I apologize for the noncreative variable names. :) Anyway, a quick
explication in case you haven't used Python much:
The first line (after importing random) opens a file called 'filename'
for reading and puts it into a file object called listfile.
The second line reads every line in listfile and puts it into a list of
strings called albumlist. albumlist[0] is the first line, albumlist[1]
is the second line, and so on.
The third line just closes the file, which is no longer needed.
The fourth line prints albumlist[#] where # is a random number between 0
(the first line) and len(albumlist). If the file is 5 lines, then
len(albumlist) returns 5, the last line of the file is albumlist[4], and
randrange will give us a number between 0 and 4 (correlating with lines
1 through 5).
I like Python. :)
Sorry for the excessive explanation if you didn't need it; it's sunday
and I'm bored.
--
Tom
"Tact is the ability to describe others as they see themselves."
-Abraham Lincoln
Reply to: