Using pathlib
to facilitate path manipulation on top of tempfile
makes it possible to create new paths with the /
path operator of pathlib:
import tempfilefrom pathlib import Pathwith tempfile.TemporaryDirectory() as tmpdirname:temp_dir = Path(tmpdirname)file_name = temp_dir / "test.txt"file_name.write_text("bla bla bla")print(temp_dir, temp_dir.exists())# /tmp/tmp81iox6s2 Trueprint(file_name, "contains", file_name.open().read())# /tmp/tmp81iox6s2/test.txt contains bla bla bla
Outside the context manager, files have been destroyed
print(temp_dir, temp_dir.exists())# /tmp/tmp81iox6s2 Falseprint(file_name, file_name.exists())# /tmp/tmp81iox6s2/test.txt False
In python 3.2 and later, there is a useful contextmanager for this in the stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory
If I get your question correctly, you want to also know the names of the files generated inside the temporary directory?If so, try this:
import osimport tempfilewith tempfile.TemporaryDirectory() as tmp_dir:# generate some random files in itfiles_in_dir = os.listdir(tmp_dir)