Skip to content

TEMPORARY FILES - Creating and using temporary files safely

Python
#!/usr/bin/env python3
"""
TEMPORARY FILES - Creating and using temporary files safely
Demonstrates various temporary file operations
"""

import os
import tempfile
import time

print("=" * 60)
print("TEMPORARY FILES - Working with Temp Storage")
print("=" * 60)

# Example 1: Get temp directory
print("\n1. System Temporary Directory")
print("-" * 40)
temp_dir = tempfile.gettempdir()
print(f"  Temp directory: {temp_dir}")
print(f"  Exists: {os.path.exists(temp_dir)}")

# Example 2: Create temp file manually
print("\n2. Manual Temporary File")
print("-" * 40)
temp_path = os.path.join(temp_dir, f"mytemp_{int(time.time())}.txt")

with open(temp_path, 'w') as f:
    f.write("Temporary data\n")
    print(f"  Created: {temp_path}")

with open(temp_path, 'r') as f:
    print(f"  Content: {f.read().strip()}")

# Clean up manually
os.remove(temp_path)
print(f"  Removed: {temp_path}")

# Example 3: Using tempfile.NamedTemporaryFile
print("\n3. Named Temporary File (Auto-Delete)")
print("-" * 40)

# Create temp file (deleted automatically when closed)
with tempfile.NamedTemporaryFile(mode='w', delete=True) as tf:
    print(f"  Temp file: {tf.name}")
    print(f"  Exists: {os.path.exists(tf.name)}")

    tf.write("This is temporary\n")
    tf.write("Will be deleted automatically\n")
    tf.flush()

    # Read it back
    with open(tf.name, 'r') as f:
        print(f"  Content: {f.read()}")

print(f"  After context: exists = {os.path.exists(tf.name)}")

# Example 4: Temp file that persists
print("\n4. Named Temporary File (Keep)")
print("-" * 40)

with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tf:
    temp_name = tf.name
    print(f"  Temp file: {temp_name}")

    tf.write("This file will persist\n")

print(f"  After context: exists = {os.path.exists(temp_name)}")

with open(temp_name, 'r') as f:
    print(f"  Content: {f.read().strip()}")

# Clean up manually
os.remove(temp_name)
print(f"  Manually removed")

# Example 5: Temp file with specific prefix/suffix
print("\n5. Temporary File with Prefix/Suffix")
print("-" * 40)

with tempfile.NamedTemporaryFile(prefix='myapp_', suffix='.log', delete=False) as tf:
    temp_name = tf.name
    basename = os.path.basename(temp_name)
    print(f"  Filename: {basename}")
    print(f"  Starts with 'myapp_': {basename.startswith('myapp_')}")
    print(f"  Ends with '.log': {basename.endswith('.log')}")

os.remove(temp_name)

# Example 6: Temporary directory
print("\n6. Temporary Directory")
print("-" * 40)

with tempfile.TemporaryDirectory() as td:
    print(f"  Temp dir: {td}")
    print(f"  Exists: {os.path.exists(td)}")

    # Create files in temp directory
    file1 = os.path.join(td, "file1.txt")
    file2 = os.path.join(td, "file2.txt")

    with open(file1, 'w') as f:
        f.write("File 1 content\n")

    with open(file2, 'w') as f:
        f.write("File 2 content\n")

    files = os.listdir(td)
    print(f"  Files created: {files}")

print(f"  After context: exists = {os.path.exists(td)}")

# Example 7: Using temp file for processing
print("\n7. Processing Data Through Temp File")
print("-" * 40)

data = ["apple", "banana", "cherry", "date", "elderberry"]

# Write to temp file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf:
    temp_name = tf.name
    for item in data:
        tf.write(f"{item}\n")

print(f"  Wrote {len(data)} items to temp file")

# Process temp file
processed = []
with open(temp_name, 'r') as f:
    for line in f:
        processed.append(line.strip().upper())

print(f"  Processed: {processed}")

os.remove(temp_name)

# Example 8: Temp file as swap space
print("\n8. Using Temp File for Sorting Large Data")
print("-" * 40)

# Simulate large dataset
large_data = [f"Item {i:04d}" for i in range(100, 0, -1)]

# Write unsorted to temp file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf:
    temp_name = tf.name
    for item in large_data:
        tf.write(f"{item}\n")

print(f"  Wrote {len(large_data)} items")

# Read, sort, write back
with open(temp_name, 'r') as f:
    lines = f.readlines()

lines.sort()

sorted_file = os.path.join(tempfile.gettempdir(), "sorted_output.txt")
with open(sorted_file, 'w') as f:
    f.writelines(lines)

print(f"  Sorted to: {sorted_file}")
print(f"  First 3: {[lines[i].strip() for i in range(3)]}")

os.remove(temp_name)
os.remove(sorted_file)

# Example 9: Temp file for file transformation
print("\n9. File Transformation via Temp File")
print("-" * 40)

source = os.path.join(tempfile.gettempdir(), "source.txt")
with open(source, 'w') as f:
    f.write("hello world\n")
    f.write("python programming\n")

# Transform to temp file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf:
    temp_name = tf.name

    with open(source, 'r') as src:
        for line in src:
            tf.write(line.upper())

# Replace original with temp
os.remove(source)
os.rename(temp_name, source)

print(f"  Transformed file in place")
with open(source, 'r') as f:
    print(f"  Result: {f.read()}")

os.remove(source)

# Example 10: Multiple temp files
print("\n10. Working with Multiple Temp Files")
print("-" * 40)

temp_files = []

# Create multiple temp files
for i in range(3):
    tf = tempfile.NamedTemporaryFile(mode='w', delete=False, prefix=f'part{i}_')
    tf.write(f"Content of part {i}\n")
    temp_files.append(tf.name)
    tf.close()

print(f"  Created {len(temp_files)} temp files")

# Process all
for i, tf_name in enumerate(temp_files):
    with open(tf_name, 'r') as f:
        print(f"  Part {i}: {f.read().strip()}")

# Clean up all
for tf_name in temp_files:
    os.remove(tf_name)

print("  All temp files removed")

# Example 11: Temp file for caching
print("\n11. Simple Cache Using Temp File")
print("-" * 40)

cache_file = os.path.join(tempfile.gettempdir(), "cache.txt")

# Check if cache exists
if os.path.exists(cache_file):
    print("  Cache hit!")
    with open(cache_file, 'r') as f:
        cached_data = f.read()
    print(f"  Cached: {cached_data.strip()}")
else:
    print("  Cache miss - computing...")
    result = "Expensive computation result"

    with open(cache_file, 'w') as f:
        f.write(result)
    print(f"  Cached: {result}")

# Clean up
if os.path.exists(cache_file):
    os.remove(cache_file)

print("\n" + "=" * 60)
print("Key Points:")
print("  - tempfile.gettempdir() for temp directory")
print("  - NamedTemporaryFile for auto-cleanup")
print("  - TemporaryDirectory for temp folders")
print("  - Use delete=False to keep temp files")
print("  - Perfect for intermediate processing")
print("=" * 60)