One common problem is to open a unique temporary file to hold
intermediate results. There are two ways to do this: the
os
module and the tempfile
module. The os
module has a subtle security flaw,
so it isn't recommended.
The tempfile
module creates a temporary
file in the most secure and reliable manner. The
tempfile
module includes an internal function,
mkstemp
which dioes the hard work of creating a
unique temporary file.
-
tempfile.TemporaryFile〈
mode
〉〈
suffix
〉〈
prefix
〉〈
directory
〉
→ file
-
This function creates a file which is automatically deleted
when it is closed. All of the parameters are optional. By default,
the mode is 'w+b'
, allowing updating. The keyword
parameters
suffix
,
prefix
and
directory
provide some structure to the name assigned to the file. The
suffix
should include the dot, for example
suffix='.tmp'
.
-
tempfile.NamedTemporaryFile〈
mode
〉〈
suffix
〉〈
prefix
〉〈
directory
〉
→ file
-
This function is similar to
TemporaryFile
; it creates a file which is
automatically deleted when it is closed. The temporary file,
however, is guaranteed to be visible on the file system while the
file is open.
-
tempfile.mkstemp〈
suffix
〉〈
prefix
〉〈
directory
〉
→
fd
, file
-
This function does the essential job of creating a temporary
file. It returns a file descriptor as well as the name of the
file. The file is not automatically deleted. If necessary, the
file created by this function can be explicitly deleted with
os.remove
.
import tempfile, os
fd, tempName = tempfile.mkstemp( '.d1' )
temp= open( tempName, 'w+' )
Some Processing...
This fragment will create a unique temporary file name with an
extension of .d1
. Since the name is guaranteed to
be unique, this can be used without fear of damaging or overwriting any
other file.