Often, I find myself needing to create multiple temporary files that are related. It would be nice if tempfile.TemporaryDirectory
could make that easier for me using something like this:
with tempfile.TemporaryDirectory() as temp_dir:
fd1, temp_file1_path = temp_dir.mkstemp()
fd2, temp_file2_path = temp_dir.mkstemp()
# Do something with the files...
Which would be equivalent to:
with tempfile.TemporaryDirectory() as temp_dir:
fd1, temp_file1_path = tempfile.mkstemp(dir=temp_dir)
fd2, temp_file2_path = temp_dir.mkstemp(dir=temp_dir)
# Do something with the files...
TemporaryDirectory
should similarly provide a .mkdtemp()
.
This will work nice with how .mkstemp()
doesn’t handle deleting the file since it will be cleaned up with the temporary directory if needed.
This way of adding it:
- Doesn’t support using
NamedTemporaryFile
. - Doesn’t support extending this pattern with sub-directories using
.mkdtemp()
as it returns the absolute pathname and not anotherTemporaryDirectory
. - Doesn’t have very Pythonic method names.
So I also thought about having something like this:
with tempfile.TemporaryDirectory() as temp_dir:
named_tempfile1 = temp_dir.named_temporary_file()
sub_tempdir1 = temp_dir.temporary_directory()
# Do something with the files...
Which would support all arguments supported by NamedTemporaryFile
and TemporaryDirectory
except those related to deletion and cleanup as they are handled by the top temporary directory.
This feels a bit less consistent with current tempfile functions but has less limitations.
Maybe this idea isn’t really useful since this doesn’t save many characters, but at least in my experience:
- It’s useful to created multiple temporary files and multiple nested temporary directories that organize things but ultimately all serve the same purpose.
- It’s nice not have to worry about deletion policies for the inner files, as you either get to keep the entire directory or none of it.
The changes needed to implemented this don’t seem very big, but I am willing (and happy!) to work on a PR for this if needed.