Resize Disk Partitions in Python (Mock Script)

A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.

Easy Python 3.7+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

52 lines
Python 3.7+
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict


@dataclass
class Partition:
    name: str
    size_gb: int
    mount_point: str

    def to_dict(self) -> Dict[str, object]:
        return {
            "name": self.name,
            "size_gb": self.size_gb,
            "mount_point": self.mount_point,
        }


def resize_partition(partition: Partition, new_size_gb: int) -> Partition:
    """Resize a partition to the specified size (mock operation)."""
    if new_size_gb <= 0:
        raise ValueError("New size must be positive")
    if new_size_gb < 2:
        print(f"Warning: {partition.name} is very small ({new_size_gb} GB)")

    old_size = partition.size_gb
    partition.size_gb = new_size_gb
    print(f"Resized {partition.name} from {old_size} GB to {new_size_gb} GB")
    return partition


def main() -> None:
    # Simulate inspecting the disk and performing the resize
    disk = {
        "/dev/sda": Partition(name="/dev/sda1", size_gb=50, mount_point="/"),
        "/dev/sda": Partition(name="/dev/sda2", size_gb=100, mount_point="/home"),
    }

    # Perform resize on the root partition
    target = disk["/dev/sda"]
    resized = resize_partition(target, 80)

    # Output the updated disk layout as JSON for verification
    layout = [p.to_dict() for p in disk.values()]
    print(json.dumps({"disk": "/dev/sda", "partitions": layout}, indent=2))


if __name__ == "__main__":
    main()

Output

stdout
Resized /dev/sda1 from 50 GB to 80 GB
{
  "disk": "/dev/sda",
  "partitions": [
    {
      "name": "/dev/sda1",
      "size_gb": 80,
      "mount_point": "/"
    },
    {
      "name": "/dev/sda2",
      "size_gb": 100,
      "mount_point": "/home"
    }
  ]
}

How it works

The script uses a @dataclass to define a Partition model with fields for name, size, and mount point. The resize_partition function validates the new size (must be positive and warns for very small sizes) before mutating the object in place. Each partition can convert itself to a dictionary via to_dict(), which makes serialization to JSON straightforward. The main() function simulates a disk with two partitions and resizes the root one, then prints the complete updated layout for verification.

Common mistakes

  • Forgetting to validate that the new size is a positive number before calling `shrink` or `grow` operations
  • Using the same key `/dev/sda` for multiple partitions in the dict, which overwrites earlier entries
  • Mutating the partition object without checking whether the disk has enough free space for the new size

Variations

  1. Use `functools.total_ordering` to allow comparing and sorting partitions by size
  2. Add a `free_space_gb` field and verify enough headroom before allowing a resize operation

Real-world use cases

  • Automation scripts that simulate or preview partition changes before performing real operations on production servers
  • Testing disk management tools in CI pipelines without touching actual hardware or virtual machine disks
  • Generating human-readable JSON reports of disk layouts for infrastructure documentation and audit trails

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.