Skip to content

Instantly share code, notes, and snippets.

@joshbarrass
Last active September 21, 2018 16:20
Show Gist options
  • Save joshbarrass/c2df525462a567718b4e72c028e7c3ed to your computer and use it in GitHub Desktop.
Save joshbarrass/c2df525462a567718b4e72c028e7c3ed to your computer and use it in GitHub Desktop.
Old utility I wrote for getting and sorting folders by size.
#!/usr/bin/env python2
import os
from docopt import docopt
def get_size(start_path = '.'):
"""Gets the size of the path in bytes."""
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.isfile(fp):
total_size += os.path.getsize(fp)
return (start_path,total_size)
def list_sizes(start_dir,size_measurement="MB",verbose=False,exceptions=False):
"""Lists the size of the chosen directory."""
if size_measurement == "B":
offset = 1.0
elif size_measurement == "KB":
offset = 1024.0
elif size_measurement == "MB":
offset = 1048576.0
elif size_measurement == "GB":
offset = 1073741824.0
else:
print "Unknown size. Defaulting to MB."
offset = 1024.0
dirs = []
if not os.path.isabs(start_dir):
start_dir = os.path.join(os.getcwd(),start_dir)
os.chdir(start_dir)
for thing in os.listdir(start_dir):
if os.path.isdir(os.path.join(start_dir,thing)):
dirs.append(os.path.join(start_dir,thing))
if verbose:
print "Added dir",thing
else:
if verbose:
print thing,"not a directory."
sizes = []
for x in dirs:
try:
sizes.append(get_size(x))
except Exception,e:
print "Failed to get",x
if verbose or exceptions:
print e
sorted_sizes = sorted(sizes,key=lambda obj:obj[1],reverse=True)
print "\n"
for x in sorted_sizes:
print x[0],":",str(float(x[1])/offset)+size_measurement
__doc__ =\
"""Improved folder size tools.
Used for getting and sorting sizes of folders to aid in freeing hard drive space.
It is recommended to pipe this utility into something such as less.
Usage:
folder_size.py -h
folder_size.py [-veu unit] <path>
Options:
-h --help Show this
-u --unit unit Specify unit. Valid units are: B, KB, MB, GB. Default is MB.
-v --verbose Display extra info
-e --exceptions Display exceptions
"""
if __name__ == "__main__":
arguments = docopt(__doc__)
if arguments.has_key("--unit") and arguments["--unit"] != None:
unit = arguments["--unit"]
else:
unit = "MB"
if arguments.has_key("--verbose"):
verbose = arguments["--verbose"]
else: verbose = False
if arguments.has_key("--exceptions"):
exceptions = arguments["--exceptions"]
else: exceptions = False
if arguments.has_key("<path>") and arguments["<path>"] != None and os.path.isdir(arguments["<path>"]):
list_sizes(arguments["<path>"],unit,verbose,exceptions)
else:
print "Directory '"+arguments["<path>"]+"' does not exist!"
Copyright 2018 Joshua Barrass
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment