Name

tempnam, tmpnam

Synopsis

tempnam(dir=None,prefix=None)
tmpnam( )

Returns an absolute path usable as the name of a new temporary file. If dir is None, the path uses the directory normally used for temporary files on the current platform; otherwise the path uses dir. If prefix is not None, it should be a short string to be prefixed to the temporary file’s name. tempnam never returns the name of any already existing file. Your program must create the temporary file, use the file, and remove the file when done, as in the following snippet:

import os
def work_on_temporary_file(workfun):
    nam = os.tempnam( )
    fil = open(nam, 'rw+')
    try:
        workfun(fil)
    finally:
        fil.close( )
        os.remove(nam)

tmpnam is a synonym for tempnam. However, tmpnam does not accept arguments, and always behaves like tempnam(None,None). tempnam and tmpnam are potential weaknesses in your program’s security, and recent versions of Python emit a warning the first time your program calls these functions to alert you to this fact. See Chapter 17 for information about ways in which your program can interact with warnings.

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.