13.1. Tempfile

13.1.1. Create Temporary File

from tempfile import TemporaryFile


file = TemporaryFile()
file.write(b'Hello world!')
file.seek(0)
file.read()
file.close()

13.1.2. Context Manager

  • preferred

from tempfile import TemporaryFile


with TemporaryFile() as file:
    file.write(b'Hello world!')
    file.seek(0)
    file.read()

13.1.3. Temporary Directory

from tempfile import TemporaryDirectory


with TemporaryDirectory() as dir:
    print('created temporary directory', dir)