Understanding tempfile.TemporaryFile
Karthik Gurusamy
kar1107 at gmail.com
Fri Dec 28 15:15:00 EST 2007
On Dec 27, 7:36 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Thu, 27 Dec 2007 21:17:01 -0600, Shane Geiger wrote:
> > import tempfile
> > tmp = tempfile.mktemp()
>
> > import os
> > os.remove(tmp)
>
> Not only does that not answer the Original Poster's question, but I don't
> think it does what you seem to think it does.
>
> >>> tmp = tempfile.mktemp()
> >>> tmp
> '/tmp/tmpZkS0Gj'
> >>> type(tmp)
> <type 'str'>
> >>> import os
> >>> os.remove(tmp)
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> OSError: [Errno 2] No such file or directory: '/tmp/tmpZkS0Gj'
>
> You might like to read help(tempfile.mktemp).
>
> (By the way... the whole point of using tempfile is to avoid needing to
> delete the file by hand afterwards.)
FWIW tempfile.mkstemp needs explicit user deletion. And
tempfile.mkstemp is recommended over tempfile.mktemp due to security
reasons.
Help on function mkstemp in module tempfile:
mkstemp(suffix='', prefix='tmp', dir=None, text=False)
mkstemp([suffix, [prefix, [dir, [text]]]])
User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
If 'suffix' is specified, the file name will end with that suffix,
otherwise there will be no suffix.
If 'prefix' is specified, the file name will begin with that
prefix,
otherwise a default prefix is used.
If 'dir' is specified, the file will be created in that directory,
otherwise a default directory is used.
If 'text' is specified and true, the file is opened in text
mode. Else (the default) the file is opened in binary mode. On
some operating systems, this makes no difference.
The file is readable and writable only by the creating user ID.
If the operating system uses permission bits to indicate whether a
file is executable, the file is executable by no one. The file
descriptor is not inherited by children of this process.
Caller is responsible for deleting the file when done with it.
<-------
>>>
Karthik
>
> --
> Steven
More information about the Python-list
mailing list