Skip to content

PATH CHECKING - Using os.path.exists(), isfile(), isdir()

Python
#!/usr/bin/env python3
"""
PATH CHECKING - Using os.path.exists(), isfile(), isdir()
Demonstrates checking file and directory existence
"""

import os
import tempfile
import shutil

print("=" * 60)
print("PATH CHECKING - Existence and Type Detection")
print("=" * 60)

temp_dir = tempfile.gettempdir()
test_dir = os.path.join(temp_dir, "path_check_demo")
os.makedirs(test_dir, exist_ok=True)

# Create test items
test_file = os.path.join(test_dir, "test.txt")
test_subdir = os.path.join(test_dir, "subdir")

with open(test_file, 'w') as f:
    f.write("test")
os.makedirs(test_subdir)

print(f"Created test environment: {test_dir}\n")

# Example 1: os.path.exists()
print("1. os.path.exists() - Check if Path Exists")
print("-" * 40)
paths_to_check = [
    test_file,
    test_subdir,
    os.path.join(test_dir, "nonexistent.txt"),
    test_dir
]

for path in paths_to_check:
    exists = os.path.exists(path)
    print(f"  {os.path.basename(path):20s}: {exists}")

# Example 2: os.path.isfile()
print("\n2. os.path.isfile() - Check if Regular File")
print("-" * 40)
items = [test_file, test_subdir, test_dir]
for item in items:
    is_file = os.path.isfile(item)
    print(f"  {os.path.basename(item) or 'test_dir':20s}: {is_file}")

# Example 3: os.path.isdir()
print("\n3. os.path.isdir() - Check if Directory")
print("-" * 40)
for item in items:
    is_dir = os.path.isdir(item)
    print(f"  {os.path.basename(item) or 'test_dir':20s}: {is_dir}")

# Example 4: Combined type detection
print("\n4. Detect Item Type")
print("-" * 40)

def get_path_type(path):
    """Determine path type"""
    if not os.path.exists(path):
        return "does not exist"
    elif os.path.isfile(path):
        return "file"
    elif os.path.isdir(path):
        return "directory"
    elif os.path.islink(path):
        return "symbolic link"
    else:
        return "other"

for item in items:
    path_type = get_path_type(item)
    print(f"  {os.path.basename(item) or 'test_dir':20s}: {path_type}")

# Example 5: Validate before operations
print("\n5. Validate Before File Operations")
print("-" * 40)

def safe_read_file(filepath):
    """Safely read file with validation"""
    if not os.path.exists(filepath):
        return "ERROR: File does not exist"
    if not os.path.isfile(filepath):
        return "ERROR: Path is not a file"
    with open(filepath, 'r') as f:
        return f.read()

print(f"  Reading {os.path.basename(test_file)}:")
content = safe_read_file(test_file)
print(f"    Result: {content.strip()}")

print(f"  Reading directory:")
content = safe_read_file(test_subdir)
print(f"    Result: {content}")

# Example 6: Check multiple conditions
print("\n6. Check Multiple Conditions")
print("-" * 40)

empty_file = os.path.join(test_dir, "empty.txt")
with open(empty_file, 'w') as f:
    pass  # Empty file

def file_info(filepath):
    """Get comprehensive file information"""
    info = {
        'exists': os.path.exists(filepath),
        'is_file': os.path.isfile(filepath),
        'is_dir': os.path.isdir(filepath),
        'readable': os.access(filepath, os.R_OK) if os.path.exists(filepath) else False,
        'writable': os.access(filepath, os.W_OK) if os.path.exists(filepath) else False,
        'size': os.path.getsize(filepath) if os.path.isfile(filepath) else 0
    }
    return info

info = file_info(test_file)
print(f"  {os.path.basename(test_file)}:")
for key, value in info.items():
    print(f"    {key:12s}: {value}")

# Example 7: Existence check in loops
print("\n7. Filter Existing Paths")
print("-" * 40)
paths_to_check = [
    os.path.join(test_dir, "file1.txt"),
    os.path.join(test_dir, "file2.txt"),
    test_file,
    os.path.join(test_dir, "missing.txt"),
    test_subdir
]

# Create some files
for i in [1, 2]:
    with open(os.path.join(test_dir, f"file{i}.txt"), 'w') as f:
        f.write(f"File {i}")

existing = [p for p in paths_to_check if os.path.exists(p)]
print(f"  Checked {len(paths_to_check)} paths")
print(f"  Found {len(existing)} existing:")
for path in existing:
    print(f"    {os.path.basename(path)}")

# Example 8: Type-specific filtering
print("\n8. Separate Files and Directories")
print("-" * 40)
all_items = [os.path.join(test_dir, item) for item in os.listdir(test_dir)]

files = [item for item in all_items if os.path.isfile(item)]
dirs = [item for item in all_items if os.path.isdir(item)]

print(f"  Files: {len(files)}")
for f in files:
    print(f"    {os.path.basename(f)}")

print(f"  Directories: {len(dirs)}")
for d in dirs:
    print(f"    {os.path.basename(d)}/")

# Example 9: Check before deletion
print("\n9. Safe Deletion with Checks")
print("-" * 40)

def safe_delete(path):
    """Delete file or directory safely"""
    if not os.path.exists(path):
        print(f"  Path doesn't exist: {os.path.basename(path)}")
        return False

    if os.path.isfile(path):
        os.remove(path)
        print(f"  Deleted file: {os.path.basename(path)}")
        return True

    if os.path.isdir(path):
        if not os.listdir(path):
            os.rmdir(path)
            print(f"  Deleted empty dir: {os.path.basename(path)}")
            return True
        else:
            print(f"  Dir not empty: {os.path.basename(path)}")
            return False

safe_delete(empty_file)
safe_delete(test_subdir)
safe_delete(os.path.join(test_dir, "nonexistent.txt"))

# Example 10: Path validation
print("\n10. Path Validation Function")
print("-" * 40)

def validate_path(path, must_exist=True, must_be_file=False, must_be_dir=False):
    """Validate path against criteria"""
    errors = []

    if must_exist and not os.path.exists(path):
        errors.append("Path does not exist")

    if must_be_file and not os.path.isfile(path):
        errors.append("Path is not a file")

    if must_be_dir and not os.path.isdir(path):
        errors.append("Path is not a directory")

    return len(errors) == 0, errors

# Test validation
valid, errors = validate_path(test_file, must_exist=True, must_be_file=True)
print(f"  Validate {os.path.basename(test_file)} as file: {valid}")

valid, errors = validate_path(test_file, must_be_dir=True)
print(f"  Validate {os.path.basename(test_file)} as dir: {valid} ({errors})")

# Cleanup
shutil.rmtree(test_dir)

print("\n" + "=" * 60)
print("Key Points:")
print("  - os.path.exists() checks if path exists")
print("  - os.path.isfile() checks if regular file")
print("  - os.path.isdir() checks if directory")
print("  - os.path.islink() checks if symbolic link")
print("  - Always validate before operations")
print("=" * 60)