Created
May 1, 2025 18:20
-
-
Save aspotton/8f8da1ab234c382d9c779654f2241308 to your computer and use it in GitHub Desktop.
Create a sparse disk image from a given device. Used on Linux.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To write the sparse image back to a device/drive/sdcard:
sudo dd if=sdcard.sparse.raw of=/dev/sdX bs=4M status=progress