tempfile.mkstemp and os.fdopen

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Tue Aug 28 21:48:34 CEST 2007


In article <1188323759.955043.317630 at 19g2000hsx.googlegroups.com>,
 billiejoex <gnewsg at gmail.com> wrote:

> Hi there.
> I'm trying to generate a brand new file with a unique name by using
> tempfile.mkstemp().
> In conjunction I used os.fdopen() to get a wrapper around file
> properties (write & read methods, and so on...) but 'name' attribute
> does not contain the correct file name. Why?
> 
> >>> import os
> >>> import tempfile
> >>> fileno, name = tempfile.mkstemp(prefix='ftpd.', dir=os.getcwd())
> >>> fd = os.fdopen(fileno, 'wb')
> >>> fd.name
> <fdopen>
> 
> Moreover, I'd like to know if I'm doing fine. Does this approach avoid
> race conditions or other types of security problems?
> 
> Thanks in advance

In brief, since os.fdopen() only has access to the file descriptor, it 
does not have a convenient way to obtain the file's name.  However, you 
might also want to look at the TemporaryFile and NamedTemporaryFile 
classes in the tempfile module -- these expose a file-like API, 
including a .name attribute.

Assuming tempfile.mkstemp() is implemented properly, I think what you 
are doing should be sufficient to avoid the obvious file-creation race 
condition.

Cheers,
-M

-- 
Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA



More information about the Python-list mailing list