Python3 script to zero fill the disk

From docs
Revision as of 15:11, 3 April 2022 by Numberformat (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This page has the python script that can be used to zero fill the empty space on a disk. Doing this helps save space when compressing the image file.

First step is to insert and mount the disk on a Linux based machine. Raspberry Pi works well for this.

Insert into the Linux machine and find the device id using

sudo lsblk

mount the device to a directory name for example mnt

Then run the following python script.

python3 zero.py mnt

import os
import shutil
import time

import argparse

parser = argparse.ArgumentParser(description='Zero fills the file system for the purpose of disk imaging and compression')
parser.add_argument('basepath', help='basepath is required.')
args = parser.parse_args()

# get space available on drive
total, used, free = shutil.disk_usage(args.basepath)

# make a byte array
buff = bytearray(1048576*100)

tempdir = os.path.join(args.basepath, f"files_tmp")
if not os.path.exists(tempdir): os.makedirs(tempdir)
print(f"tempdir : {tempdir} created to hold zero fill files.")
for i in range(int(free/len(buff))):
  ff = open(os.path.join(tempdir, f"file_{i}.tmp"), "wb")
  start = time.time()
  byteswritten = ff.write(buff)
  end = time.time()
  speed = byteswritten/1048576 / (end-start)
  total, used, free = shutil.disk_usage(tempdir)
  print(f'free: {int(free/(1024*1024))} Mb, speed = {speed:.2f} Mb/sec')
  ff.close()
# create the last temp file
ff = open(os.path.join(tempdir, f"file_final.tmp"), "wb")
byteswritten = ff.write(bytearray(free))
ff.close()
# finally delete the temp
print("All remaining space on drive filled.")
ans = input(f"Are you sure you want to delete: {tempdir} (Y/N)? ")
if "Y" == ans.upper():
  if os.path.exists(tempdir): shutil.rmtree(tempdir)