# Simple Key-Value Store with Shelve

This utility creates a persistent, dictionary-like key-value store using the `shelve` module. It allows you to store strings, numbers, and other Python objects to a local file and retrieve them later via the command line.

**Modules Used:**
*   [[programming/python/modules/shelve-module|shelve]]: To manage the persistent storage.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.

## The Code

Save this as `kv_store.py`.

```python
import shelve
import argparse
import sys

DB_FILE = "my_store"

def add_item(key, value):
    with shelve.open(DB_FILE, writeback=True) as db:
        db[key] = value
        print(f"Stored: '{key}' -> '{value}'")

def get_item(key):
    with shelve.open(DB_FILE) as db:
        if key in db:
            print(f"{key}: {db[key]}")
        else:
            print(f"Error: Key '{key}' not found.")

def delete_item(key):
    with shelve.open(DB_FILE) as db:
        if key in db:
            del db[key]
            print(f"Deleted key: '{key}'")
        else:
            print(f"Error: Key '{key}' not found.")

def list_items():
    with shelve.open(DB_FILE) as db:
        if not db:
            print("Store is empty.")
            return
            
        print(f"{'Key':<20} {'Value'}")
        print("-" * 40)
        for key, value in db.items():
            print(f"{key:<20} {value}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple Key-Value Store using Shelve")
    subparsers = parser.add_subparsers(dest="command", help="Command to run")

    # Add Command
    add_parser = subparsers.add_parser("add", help="Add a key-value pair")
    add_parser.add_argument("key", help="The key")
    add_parser.add_argument("value", help="The value")

    # Get Command
    get_parser = subparsers.add_parser("get", help="Retrieve a value by key")
    get_parser.add_argument("key", help="The key to retrieve")

    # Delete Command
    del_parser = subparsers.add_parser("delete", help="Delete a key-value pair")
    del_parser.add_argument("key", help="The key to delete")

    # List Command
    list_parser = subparsers.add_parser("list", help="List all keys and values")

    args = parser.parse_args()

    if args.command == "add":
        add_item(args.key, args.value)
    elif args.command == "get":
        get_item(args.key)
    elif args.command == "delete":
        delete_item(args.key)
    elif args.command == "list":
        list_items()
    else:
        parser.print_help()
```

## Usage

```bash
# Add items
python kv_store.py add username "admin"
python kv_store.py add port 8080

# Retrieve an item
python kv_store.py get username

# List all items
python kv_store.py list

# Delete an item
python kv_store.py delete port
```

[[programming/python/python]]