ruk·si

🐍 Python
Temporary Files

Updated at 2019-06-08 21:04

You can create temporary file-like objects in Python. They act as temporary storage and are deleted when the file is closed explicitly or by garbage collection. You can also use temporary file as a context manager.

import tempfile

tf = tempfile.TemporaryFile()
tf.write(b'hello')
tf.seek(0)
assert tf.read() == b'hello'
tf.close()

with tempfile.TemporaryFile() as tf:
    tf.write(b'bye')
    tf.seek(0)
    assert tf.read() == b'bye'

You can create actual temporary files. There will be a real file in the file system. It will open the file for instant access, so keep in mind that opening it a second time without closing the first one first can crash in some operating systems. Use delete=False if you don't wish to automatically delete the file on close.

import tempfile

tf = tempfile.NamedTemporaryFile()
assert isinstance(tf.name, str)
tf.write(b'hello')
tf.seek(0)
assert tf.read() == b'hello'
tf.close()

with tempfile.NamedTemporaryFile() as tf:
    tf.write(b'bye')
    tf.seek(0)
    assert tf.read() == b'bye'

Temporary directories are also available. You can create temporary directories that are deleted when either the object is destroyed, cleanup is called or the context manager scope ends.

import os
import tempfile

td = tempfile.TemporaryDirectory()
assert isinstance(td, tempfile.TemporaryDirectory)
tf = os.path.join(td.name, 'greeting.txt')
with open(tf, 'w') as f:
    f.write('hello')
with open(tf, 'r') as f:
    assert f.read() == 'hello'
td.cleanup()

with tempfile.TemporaryDirectory() as td:
    assert isinstance(td, str)
    tf = os.path.join(td, 'greeting.txt')
    with open(tf, 'w') as f:
        f.write('hello')
    with open(tf, 'r') as f:
        assert f.read() == 'hello'