Creating temporary files with unique names securely, so they cannot be guessed by someone wanting to break the application or steal the data, is challenging. The tempfile module provides several functions for creating temporary file system resources securely. TemporaryFile() opens and returns an unnamed file, NamedTemporaryFile() opens and returns a named file, SpooledTemporaryFile holds its content in memory before writing to disk, and TemporaryDirectory is a context manager that removes the directory when the context is closed.

Temporary File


In [1]:
import os
import tempfile

print('Building a filename with PID:')
filename = '/tmp/guess_my_name.{}.txt'.format(os.getpid())
with open(filename, 'w+b') as temp:
    print('temp:')
    print('  {!r}'.format(temp))
    print('temp.name:')
    print('  {!r}'.format(temp.name))

# Clean up the temporary file yourself.
os.remove(filename)

print()
print('TemporaryFile:')
with tempfile.TemporaryFile() as temp:
    print('temp:')
    print('  {!r}'.format(temp))
    print('temp.name:')
    print('  {!r}'.format(temp.name))


Building a filename with PID:
temp:
  <_io.BufferedRandom name='/tmp/guess_my_name.37883.txt'>
temp.name:
  '/tmp/guess_my_name.37883.txt'

TemporaryFile:
temp:
  <_io.BufferedRandom name=53>
temp.name:
  53

In [2]:
import os
import tempfile

with tempfile.TemporaryFile() as temp:
    temp.write(b'Some data')

    temp.seek(0)
    print(temp.read())


b'Some data'

In [3]:
import tempfile

with tempfile.TemporaryFile(mode='w+t') as f:
    f.writelines(['first\n', 'second\n'])

    f.seek(0)
    for line in f:
        print(line.rstrip())


first
second

Named File


In [4]:
import os
import pathlib
import tempfile

with tempfile.NamedTemporaryFile() as temp:
    print('temp:')
    print('  {!r}'.format(temp))
    print('temp.name:')
    print('  {!r}'.format(temp.name))

    f = pathlib.Path(temp.name)

print('Exists after close:', f.exists())


temp:
  <tempfile._TemporaryFileWrapper object at 0x105563828>
temp.name:
  '/var/folders/k9/2cxh1k2115s_lw4wtq9mzj9m0000gp/T/tmpmao57w23'
Exists after close: False

Spooled File


In [6]:
import tempfile

with tempfile.SpooledTemporaryFile(max_size=100,
                                   mode='w+t',
                                   encoding='utf-8') as temp:
    print('temp: {!r}'.format(temp))
    for i in range(3):
        temp.write('This line is repeated over and over.\n')
        print(temp._rolled, temp._file)


temp: <tempfile.SpooledTemporaryFile object at 0x10561e9b0>
False <_io.StringIO object at 0x1055f0c18>
False <_io.StringIO object at 0x1055f0c18>
True <_io.TextIOWrapper name=56 mode='w+t' encoding='utf-8'>

In [7]:
import tempfile

with tempfile.SpooledTemporaryFile(max_size=1000,
                                   mode='w+t',
                                   encoding='utf-8') as temp:
    print('temp: {!r}'.format(temp))

    for i in range(3):
        temp.write('This line is repeated over and over.\n')
        print(temp._rolled, temp._file)
    print('rolling over')
    temp.rollover()
    print(temp._rolled, temp._file)


temp: <tempfile.SpooledTemporaryFile object at 0x105630780>
False <_io.StringIO object at 0x10554db88>
False <_io.StringIO object at 0x10554db88>
False <_io.StringIO object at 0x10554db88>
rolling over
True <_io.TextIOWrapper name=56 mode='w+t' encoding='utf-8'>

Temporary Directories


In [8]:
import pathlib
import tempfile

with tempfile.TemporaryDirectory() as directory_name:
    the_dir = pathlib.Path(directory_name)
    print(the_dir)
    a_file = the_dir / 'a_file.txt'
    a_file.write_text('This file is deleted.')

print('Directory exists after?', the_dir.exists())
print('Contents after:', list(the_dir.glob('*')))


/var/folders/k9/2cxh1k2115s_lw4wtq9mzj9m0000gp/T/tmp5tso4jyq
Directory exists after? False
Contents after: []

Predicting Name


In [9]:
import tempfile

with tempfile.NamedTemporaryFile(suffix='_suffix',
                                 prefix='prefix_',
                                 dir='/tmp') as temp:
    print('temp:')
    print('  ', temp)
    print('temp.name:')
    print('  ', temp.name)


temp:
   <tempfile._TemporaryFileWrapper object at 0x1055f1f28>
temp.name:
   /tmp/prefix_aa9_7ivp_suffix

Temporary File Location


In [10]:
import tempfile

print('gettempdir():', tempfile.gettempdir())
print('gettempprefix():', tempfile.gettempprefix())


gettempdir(): /var/folders/k9/2cxh1k2115s_lw4wtq9mzj9m0000gp/T
gettempprefix(): tmp