Temporary directory for documentation¶
Goal
This is the guide that provide templates for using temporary directory in the document. There are two patterns which are (1) manual clean-up and (2) with context manager where the context manager pattern is preferred.
With context manager¶
This pattern is preferred since it handles clean-up upon context exit.
In [1]:
Copied!
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as temp:
context_path = Path(temp)
print(context_path.exists())
# Create the path with parents if not existed already
context_path.mkdir(parents=True, exist_ok=True)
print(context_path.exists())
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as temp:
context_path = Path(temp)
print(context_path.exists())
# Create the path with parents if not existed already
context_path.mkdir(parents=True, exist_ok=True)
print(context_path.exists())
True False
Manaul clean-up¶
This approach is useful when multiple cells need to use the same temporary directory
In [2]:
Copied!
import tempfile
from pathlib import Path
tmpdir = tempfile.TemporaryDirectory()
path = Path(tmpdir.name) / "named_directory"
# Create the path with parents if not existed already
path.mkdir(parents=True, exist_ok=True)
print(path.exists())
# Do something in the path
tmpdir.cleanup()
# Should not exist after clean up
print(path.exists())
import tempfile
from pathlib import Path
tmpdir = tempfile.TemporaryDirectory()
path = Path(tmpdir.name) / "named_directory"
# Create the path with parents if not existed already
path.mkdir(parents=True, exist_ok=True)
print(path.exists())
# Do something in the path
tmpdir.cleanup()
# Should not exist after clean up
print(path.exists())
True False