Skip to content

Instantly share code, notes, and snippets.

@Mellen
Created March 11, 2019 17:46
Show Gist options
  • Save Mellen/21aaf4c12749469344d3394f81d30938 to your computer and use it in GitHub Desktop.
Save Mellen/21aaf4c12749469344d3394f81d30938 to your computer and use it in GitHub Desktop.
A method for seeing how a disk (on MS Windows) is used.
#! python
import os
import shutil
import argparse
import json
parser = argparse.ArgumentParser(description='Creates a report about the distribution over folders of disk use.')
parser.add_argument('drive_letter', nargs=1, metavar='drive letter', help='The drive that should be analysed.')
args = parser.parse_args()
def analyse(drive_letter):
print('Analysing', drive_letter, 'drive...')
base_dir = '{drive_letter}:\\'.format(drive_letter=drive_letter)
dir_size = 4096
total_space, space_used, space_free = shutil.disk_usage(base_dir)
bytes_remaining = space_used
print('total space: {tot}GB, used space: {used}GB, free space: {free}GB'.format(tot=total_space//2**30, used=space_used//2**30, free=space_free//2**30))
output = {base_dir: {'total_space': total_space, 'used_space': space_used, 'free_space': space_free}}
skips = 0
current_tick = '/'
for dir_name, dir_list, file_list in os.walk(base_dir):
if is_junction(dir_name):
continue
file_size = 0
files = {}
for file_name in file_list:
try:
if os.path.islink(os.path.join(dir_name, file_name)):
continue
size = os.path.getsize(os.path.join(dir_name, file_name))
files[file_name] = size
bytes_remaining -= size
print('Bytes left to analyse:', bytes_remaining, end='\r')
file_size += size
except OSError:
print('can\'t get the size of', os.path.join(dir_name, file_name))
skips += 1
the_path = dir_name.split('\\')
cur_dict = output[base_dir]
for dire in the_path[1:]:
try:
cur_dict = cur_dict[dire]
except KeyError:
cur_dict[dire] = {'file_size': file_size}
cur_dict[dire]['files'] = files
bytes_remaining -= dir_size
with open('disk_use.json', 'w') as json_output:
json_output.write(json.dumps(output))
print('finished analysis')
def is_junction(path):
mode = os.lstat(path).st_mode
return mode == 16895
if __name__ == '__main__':
analyse(args.drive_letter[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment