Skip to content

Instantly share code, notes, and snippets.

@danmaps
Last active October 25, 2016 20:28
Show Gist options
  • Save danmaps/90423f10ad8f53ce67af1ecef2d6d4f3 to your computer and use it in GitHub Desktop.
Save danmaps/90423f10ad8f53ce67af1ecef2d6d4f3 to your computer and use it in GitHub Desktop.
import os
from math import log
######################################
# http://stackoverflow.com/a/10171475
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2])
def sizeof_fmt(num):
"""Human friendly file size"""
if num > 1:
exponent = min(int(log(num, 1024)), len(unit_list) - 1)
quotient = float(num) / 1024**exponent
unit, num_decimals = unit_list[exponent]
format_string = '{:.%sf} {}' % (num_decimals)
return format_string.format(quotient, unit)
if num == 0:
return '0 bytes'
if num == 1:
return '1 byte'
######################################
def searchExt(directory,searchExt):
# Check for "." in extension input and add if necessary
if not searchExt.startswith("."):
searchExt= "."+searchExt
# Create dictionary with format {ext:[path,path,...]}
pathsDict={}
for path, dirs, files in os.walk(directory):
for f in files: pathsDict[os.path.splitext(f)[1]]=[] #instantiate with empyt list
for f in files: pathsDict[os.path.splitext(f)[1]].append(os.path.join(path,f)) # load list
# Print results
print "found",len(pathsDict.keys()),"filetypes" # entries in dictionary
for ext in sorted(pathsDict.keys()): # sort alphabetically
print len(pathsDict[ext]),"\t",ext # length of pathlist and each ext
# Print paths for the selected extension
if searchExt in pathsDict.keys(): # avoid error if file type not in dictionary
print "found",len(pathsDict[searchExt]),searchExt+"s" # length of pathlist
for filepath in pathsDict[searchExt]: # for each path in the list
print sizeof_fmt(os.stat(filepath).st_size),"\t",filepath # filesize, path
if __name__ == '__main__':
directory = r"C:\Temp"
searchExt(directory,"")
while 1==1: # repeat forever
ext = raw_input("Enter extension or ctrl-c to quit: ")
searchExt(directory,ext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment