Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Sun, 13 May 2007 18:41:16 -0300, Sick Monkey <[EMAIL PROTECTED]>  
> escribi?:

>> If anyone has a simpler way of checking to see if
>> a file already exists (prior to uploading to a server) and renaming it,
>> please let me know.

> I will ignore the "server" part...

>> Here is the code that I am using (it runs exactly the same as the linux  
>> app
>> 'arcgen').
>>      [...]
>>      t = i-1
>>      filename=string.replace(filename,".-%s" % (t),".-%s" % (i))

> If the original filename contained .-1 somewhere, you're modifying it.  
> This is safer and shorter:

> import os,string
> filename = "whoa.mp3"
> dir_path = "/u01/"
> ofilename = filename
> i = 0
> while os.path.exists(dir_path+filename):
>  filename = "%s.-%s" % (ofilename,i)
>  i += 1
> req.write(filename)


 Is it really safer?  Couldn't their still be a race condition
 (if some hostile process has write access to the directory in
 which this is being attempted)?  

 Wouldn't it be safer to import tempfile, use the t=NamedTemporaryFile()
 function therein and then use try: os.link(t.name, ...) except OSError:
 to safely rename it?

 Something like:

        import os, tempfile
        tdir = "/u01/"
        tf = tempfile.NamedTemporaryFile(dir="/u01/"

        i = 0
        while 1:
                try:
                        os.link(tf.name, os.path.join(tdir, filename)
                except OSError:
                        i += 1
                        filename = "%s.-%s" % (filename, i)
                else:
                        break

 ...???


-- 
Jim Dennis,
Starshine: Signed, Sealed, Delivered

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to