[Tutor] randomness

Roeland Rengelink r.b.rigilink@chello.nl
Sat, 16 Jun 2001 09:57:50 +0200


Hi Andrew,

My quick and dirty solution is usually to use time.time() in the
filename. But if you're creating files in multiple threads (which I
gather you're doing) there is of course an (exceedingly) small
probabilty that files are created at the same moment.

But then again, your code below theoretically suffers from the same
problem (really, it does).

This is really safe:

file_creation_lock = Lock()

class Filecreator:
   file_number = 0:
   def __call__(self):
       Filecreator.file_number += 1
       return open('%6.6i.html' % Filecreator.file_number)

filecreator = Filecreator()

And in the thread:

    def run():
        ...
        file_creation_lock.acquire()
        file = filecreator()
	file_creation_lock.release()
        ...

But, then again, this may be overkill

Hope this helps,

Roeland

Andrew Wilkins wrote:
> 
> 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?
> 
> Thanks,
> 
> Andrew
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"