[Tutor] randomness

Glen Wheeler wheelege@tsn.cc
Sat, 16 Jun 2001 17:22:10 +1000


> Hi folks
>
> What's a good way to generate a random unique file name? I can't use
> os.tempnam/os.tmpnam, are they *nix specific? I'm using Windows ME with
> Python 2.1 I could only think of this:
>
> import os,random
>
> files=os.listdir('threadhtml')
> filename=''
> while not filename:
>  n=random.randint(0,100000)
>  if not '%i.html' in files:
>   filename='%i.html'
>
> But it seems a bit yucky...can someone shed any light on the matter?
>

  Hmmm, well I just used the string modules' predefined string.letters
variable and split it into a list, then did a random number of
random.choice() grabs from it and shoved them in a filename.
  Be sure to check if the file already exists.  I think your code does not
do 'unique file name'-s as you put it :)

  Glen.