pythonunit-testingtestingtemporary-files

Python: How do I make temporary files in my test suite?


(I'm using Python 2.6 and nose.)

I'm writing tests for my Python app. I want one test to open a new file, close it, and then delete it. Naturally, I prefer that this will happen inside a temporary directory, because I don't want to trash the user's filesystem. And, it needs to be cross-OS.

How do I do it?


Solution

  • See the tempfile module in the standard library

    Here are the examples of using TemporaryFile and TemporaryDirectory as context managers:

    with tempfile.TemporaryFile() as fp:
        fp.write(b'Hello world!')
        fp.seek(0)
        fp.read()
    
    with tempfile.TemporaryDirectory() as tmpdirname:
        print('created temporary directory', tmpdirname)