[Tutor] tempfile and webbrowser

Kent Johnson kent37 at tds.net
Fri Sep 8 22:08:51 CEST 2006


Alan Gauld wrote:
>>> Use os.remove() instead.
>> os.remove() and os.unlink() are identical according to the docs; if 
>> you look at posix_module.c you can see this is true - they both map 
>> to posix_unlink().
>>
>> Kent
> 
> Maybe so, but os.remove() works on my XP box... :-)
> 
> I didn't try unlink since the OP said it didn't work. 

Did you try the OP's code with os.remove()? I doubt it works for you, 
here is what I got:

In [9]: import os, tempfile

In [10]: a = tempfile.mkstemp()

In [11]: f= open(a[1],'w')

In [12]: f.write("foo")

In [13]: f.close()

In [14]: print f.name
c:\docume~1\ktjohn~1\locals~1\temp\tmpy_3mmh

In [15]: # here some code to do some things with f

In [16]: os.unlink(f.name)
---------------------------------------------------------------------------
exceptions.OSError
Traceback (most recent call last)

D:\Projects\e3po\<ipython console>

OSError: [Errno 13] Permission denied: 
'c:\\docume~1\\ktjohn~1\\locals~1\\temp\\tmpy_3mmh'


os.remove() doesn't work either:

In [17]: os.remove(f.name)
---------------------------------------------------------------------------
exceptions.OSError
Traceback (most recent call last)

D:\Projects\e3po\<ipython console>

OSError: [Errno 13] Permission denied: 
'c:\\docume~1\\ktjohn~1\\locals~1\\temp\\tmpy_3mmh'


Maybe time for another trip to the docs:
mkstemp() returns a tuple containing an OS-level handle to an open file 
(as would be returned by os.open()) and the absolute pathname of that 
file, in that order.

Aha, mkstemp() is already opening the file, so the explicit open() 
creates a *second* handle to the open file; when it is closed, the 
original handle is still open.

Try it like this, using os.fdopen() to convert the low-level file handle 
from mkstemp() to a Python file object:

In [21]: fd, fname = tempfile.mkstemp()

In [22]: f = os.fdopen(fd, 'w')

In [23]: f.write('foo')

In [24]: f.close()

In [25]: os.unlink(fname)

Seems to work...

Kent



More information about the Tutor mailing list