Skip to content

WORKING DIRECTORY - Using os.getcwd() and os.chdir()

Python
#!/usr/bin/env python3
"""
WORKING DIRECTORY - Using os.getcwd() and os.chdir()
Demonstrates getting and changing current working directory
"""

import os
import tempfile
import shutil

print("=" * 60)
print("WORKING DIRECTORY - os.getcwd() and os.chdir()")
print("=" * 60)

# Save original directory
original_dir = os.getcwd()
print(f"Original working directory: {original_dir}\n")

# Create test environment
temp_dir = tempfile.gettempdir()
test_dir = os.path.join(temp_dir, "chdir_demo")
os.makedirs(test_dir, exist_ok=True)

# Create subdirectories
for dirname in ["dir1", "dir2", "dir3"]:
    os.makedirs(os.path.join(test_dir, dirname), exist_ok=True)

# Example 1: Get current working directory
print("1. os.getcwd() - Get Current Directory")
print("-" * 40)
cwd = os.getcwd()
print(f"  Current working directory: {cwd}")
print(f"  Type: {type(cwd)}")

# Example 2: Change directory
print("\n2. os.chdir() - Change Directory")
print("-" * 40)
print(f"  Before: {os.getcwd()}")
os.chdir(test_dir)
print(f"  After:  {os.getcwd()}")

# Example 3: Relative path operations
print("\n3. Relative Paths After chdir()")
print("-" * 40)
# Create file in current directory
with open("test.txt", 'w') as f:
    f.write("Test file\n")

print(f"  Created 'test.txt' in {os.getcwd()}")
print(f"  File exists: {os.path.exists('test.txt')}")
print(f"  Absolute path: {os.path.abspath('test.txt')}")

# Example 4: Change to subdirectory
print("\n4. Navigate to Subdirectory")
print("-" * 40)
os.chdir("dir1")
print(f"  Changed to: {os.getcwd()}")
print(f"  In directory: {os.path.basename(os.getcwd())}")

# Example 5: Change to parent directory
print("\n5. Navigate to Parent Directory (..)")
print("-" * 40)
print(f"  Before: {os.getcwd()}")
os.chdir("..")
print(f"  After:  {os.getcwd()}")

# Example 6: Absolute path change
print("\n6. Change Using Absolute Path")
print("-" * 40)
dir2_path = os.path.join(test_dir, "dir2")
print(f"  Target: {dir2_path}")
os.chdir(dir2_path)
print(f"  Now in: {os.getcwd()}")

# Example 7: Context manager for temporary directory change
print("\n7. Temporary Directory Change (Context Manager)")
print("-" * 40)

class ChangeDirectory:
    """Context manager for changing directory"""
    def __init__(self, path):
        self.path = path
        self.saved_path = None

    def __enter__(self):
        self.saved_path = os.getcwd()
        os.chdir(self.path)
        return self

    def __exit__(self, *args):
        os.chdir(self.saved_path)

os.chdir(test_dir)
print(f"  Before context: {os.getcwd()}")

with ChangeDirectory("dir3"):
    print(f"  Inside context: {os.getcwd()}")

print(f"  After context:  {os.getcwd()}")

# Example 8: List files in current directory
print("\n8. List Files in Current Directory")
print("-" * 40)
os.chdir(test_dir)
files = os.listdir(os.getcwd())
print(f"  Files in {os.path.basename(os.getcwd())}:")
for item in files:
    print(f"    {item}")

# Example 9: Error handling
print("\n9. Error Handling")
print("-" * 40)
try:
    os.chdir("/nonexistent/directory")
except FileNotFoundError:
    print("  Error: Directory does not exist")
except NotADirectoryError:
    print("  Error: Path is not a directory")

# Example 10: Safe directory change
print("\n10. Safe Directory Change Function")
print("-" * 40)

def safe_chdir(path, create=False):
    """Safely change directory with validation"""
    if not os.path.exists(path):
        if create:
            os.makedirs(path)
            print(f"  Created directory: {path}")
        else:
            print(f"  Error: Path doesn't exist: {path}")
            return False

    if not os.path.isdir(path):
        print(f"  Error: Not a directory: {path}")
        return False

    try:
        os.chdir(path)
        print(f"  Changed to: {os.getcwd()}")
        return True
    except Exception as e:
        print(f"  Error: {e}")
        return False

safe_chdir(test_dir)
safe_chdir(os.path.join(test_dir, "newdir"), create=True)

# Return to original directory
os.chdir(original_dir)
print(f"\nReturned to original directory: {os.getcwd()}")

# Cleanup
shutil.rmtree(test_dir)

print("\n" + "=" * 60)
print("Key Points:")
print("  - os.getcwd() returns current working directory")
print("  - os.chdir() changes working directory")
print("  - Use absolute paths for clarity")
print("  - Affects relative path operations")
print("  - Always restore original directory")
print("=" * 60)