How to create a unique directory name using Python?

Creating unique directory names is essential when working with temporary files or avoiding naming conflicts. Python's tempfile module provides a secure way to create unique temporary directories with proper permissions.

Using tempfile.mkdtemp()

The mkdtemp() function creates a temporary directory in the most secure manner possible. There are no race conditions in the directory's creation, and it's readable, writable, and searchable only by the creating user ID ?

import tempfile
import os

# Create a unique temporary directory
temp_dir_path = tempfile.mkdtemp()
print(f"Created directory: {temp_dir_path}")

# Check if directory exists
print(f"Directory exists: {os.path.exists(temp_dir_path)}")

# Clean up - remove the directory when done
os.rmdir(temp_dir_path)
print("Directory removed")
Created directory: /tmp/tmpx1y2z3ab
Directory exists: True
Directory removed

Customizing Directory Creation

You can customize the directory name prefix, suffix, and location ?

import tempfile
import os

# Create directory with custom prefix and suffix
temp_dir = tempfile.mkdtemp(prefix="myapp_", suffix="_temp")
print(f"Custom directory: {temp_dir}")

# Create in specific location
custom_location = "/tmp" if os.name != 'nt' else "C:\temp"
if os.path.exists(custom_location):
    temp_dir2 = tempfile.mkdtemp(dir=custom_location, prefix="data_")
    print(f"Directory in custom location: {temp_dir2}")
    os.rmdir(temp_dir2)

# Clean up
os.rmdir(temp_dir)
Custom directory: /tmp/myapp_x1y2z3ab_temp
Directory in custom location: /tmp/data_a1b2c3de

Safe Directory Management with Context Manager

For automatic cleanup, you can create a context manager ?

import tempfile
import os
import shutil
from contextlib import contextmanager

@contextmanager
def temp_directory():
    """Create a temporary directory and clean it up automatically"""
    temp_dir = tempfile.mkdtemp()
    try:
        yield temp_dir
    finally:
        shutil.rmtree(temp_dir)

# Usage with automatic cleanup
with temp_directory() as temp_dir:
    print(f"Working in: {temp_dir}")
    # Create a file in the directory
    test_file = os.path.join(temp_dir, "test.txt")
    with open(test_file, 'w') as f:
        f.write("Hello, World!")
    print(f"Created file: {test_file}")
    print(f"Directory contents: {os.listdir(temp_dir)}")
# Directory is automatically removed here

print("Directory cleaned up automatically")
Working in: /tmp/tmp1a2b3c4d
Created file: /tmp/tmp1a2b3c4d/test.txt
Directory contents: ['test.txt']
Directory cleaned up automatically

Parameters

Parameter Description Default
suffix String added at end of directory name None
prefix String added at beginning of directory name 'tmp'
dir Parent directory for the new directory System temp directory

Conclusion

Use tempfile.mkdtemp() to create unique, secure temporary directories. Remember to clean up manually with os.rmdir() or shutil.rmtree(), or use a context manager for automatic cleanup.

Updated on: 2026-03-24T18:13:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements