3

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?

DSGym
  • 2,807
  • 1
  • 6
  • 18

1 Answers1

2

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']
Romain
  • 19,910
  • 6
  • 56
  • 65