Test Files Creating a Temporal Directory in Python Unittests

Last modified:


Some Python projects need to work with files and directories, to check if the contents are written to a file or that the contents are written as expected.

To easily unit test creating, deleting and checking their contents, we can create a temporal folder that will contain all of the above generated files and work with them.


In our test code, we use the tempfile module.

This module creates temporary files and directories.

We can choose between high-level and lower-level interfaces depending on the type of test we want, main difference is that the former one handles all directories and its content removal as soon as the completion of the context or the destruction of the temporary directory object.

high-level interface

Using tempfile.TemporaryDirectory to create a temporal directory (or tempfile.TemporaryFile for files) before each method:

import tempfile

class TestExample(unittest.TestCase):

    def setUp(self):
        # Create a temporary directory
        self.test_dir = tempfile.TemporaryFile()
    def tearDown(self):
        # Close the file, the directory will be removed after the test

if __name__ == '__main__':

Using in single test

Create a temporary directory using the context manager:

import tempfile

class TestExample(unittest.TestCase):

	def test_example(self):
		with tempfile.TemporaryDirectory() as tmpdirname:
			print('created temporary directory', tmpdirname)

if __name__ == '__main__':


Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme