Temporary files and directories are super useful — but forgetting to remove them can clutter your server over time.
With Python’s contextlib.contextmanager
, you can automate cleanup so everything is deleted once your work is done.
Here’s how it works:
- When you enter the
with
block, the context manager creates the directory or file. - You perform your operations inside the block.
- Once the block exits (even if an error occurs), the
finally
section automatically cleans up by removing the directory or file.
This ensures your server stays tidy, no matter what happens during execution.
🧩 Full Code
import os
import shutil
from contextlib import contextmanager
@contextmanager
def temp_dir(dir_path: str):
"""
Context manager to create and automatically remove a temporary directory.
"""
try:
os.makedirs(dir_path, exist_ok=True)
yield dir_path
finally:
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
@contextmanager
def temp_file(file_path: str):
"""
Context manager to handle a temporary file. Removes it when done.
"""
try:
yield file_path
finally:
if os.path.exists(file_path):
os.remove(file_path)
print(f"File '{file_path}' removed successfully.")
else:
print(f"File '{file_path}' not found.")
⚙️ Example
with temp_dir("temp_folder") as d:
print(f"Working inside: {d}")
# do something in this directory
with temp_file("temp.txt") as f:
with open(f, "w") as file:
file.write("Temporary data.")
✅ Once the with
block ends, the directory and file are deleted automatically — keeping your environment clean and your code responsible.
Top comments (0)