Search code examples
pytestpython-unittestpytest-mocktemporary-directory

Generate temporary Directory with files in Python for unittesting


I want to create a temporary folder with a directory and some files:

import os
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
    Path('file.txt').touch()
    Path('file2.txt').touch()

    files_in_dir = os.listdir(tmp_dir)
    print(files_in_dir)


Expected: [file.txt,file2.txt]
Result: []

Does anyone know how to this in Python? Or is there a better way to just do some mocking?


Solution

  • You have to create the file inside the directory by getting the path of your tmp_dir. The with context does not do that for you.

    with tempfile.TemporaryDirectory() as tmp_dir:
        Path(tmp_dir, 'file.txt').touch()
        Path(tmp_dir, 'file2.txt').touch()
        files_in_dir = os.listdir(tmp_dir)
        print(files_in_dir)
    
    # ['file2.txt', 'file.txt']