When I try to convert this code to a function, it doesn't work properly. The code is supposed to take a directory and report a summary of the contents, which includes the count, max, min and average size of files by file extension. When I run outside of a function, it works, but when I try to convert to a function, it gives me the stats for only the first file type it encounters. Why is it not iterating? I'm sure its something small and obvious!
def directory_summary(a_dir):
import os
from collections import defaultdict
os.chdir(a_dir)
mydir = os.listdir(os.curdir)
filedict = {}
ext_str = 'file type:'
cnt_str = 'count:'
max_str = 'max. size:'
min_str = 'min. size:'
avg_str = 'avg. size:'
def calc_avg(num_list):
return round(sum (num_list) / len(num_list))
for file in mydir:
fileext = os.path.splitext(file)[1]
filesz = os.path.getsize(file)
filedict.setdefault(fileext,[]).append(filesz)
print ('Summary of directory contents:')
for ext, sz in filedict.items():
return print(ext_str+ext,cnt_str,len(sz),max_str,max(sz),min_str,min(sz), avg_str,calc_avg(sz))
myd = r'C:\GIS'
directory_summary(myd)