Skip to content

Instantly share code, notes, and snippets.

@aspotton
Created May 1, 2025 18:20
Show Gist options
  • Save aspotton/8f8da1ab234c382d9c779654f2241308 to your computer and use it in GitHub Desktop.
Save aspotton/8f8da1ab234c382d9c779654f2241308 to your computer and use it in GitHub Desktop.
Create a sparse disk image from a given device. Used on Linux.
#!/usr/bin/env python3
import os
import sys
BLOCK_SIZE = 4096 # 4 KB
def is_zero_block(block):
return block == b'\x00' * len(block)
def sparse_copy(src_path, dst_path):
with open(src_path, 'rb') as src, open(dst_path, 'wb') as dst:
while True:
block = src.read(BLOCK_SIZE)
if not block:
break
if is_zero_block(block):
dst.seek(BLOCK_SIZE, os.SEEK_CUR)
else:
dst.write(block)
if __name__ == "__main__":
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} /dev/sdX output.img", file=sys.stderr)
sys.exit(1)
sparse_copy(sys.argv[1], sys.argv[2])
@aspotton
Copy link
Author

aspotton commented May 1, 2025

To write the sparse image back to a device/drive/sdcard:

sudo dd if=sdcard.sparse.raw of=/dev/sdX bs=4M status=progress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment