-2

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)
4

2 回答 2

0

return在接下来的 setenece 中,让循环过早停止。

  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))

删除return

  for ext, sz in filedict.items():
    print(ext_str+ext,cnt_str,len(sz),max_str,max(sz),min_str,min(sz), avg_str,calc_avg(sz))
于 2013-09-21T15:35:16.583 回答
0

循环第一次for ext, sz in filedict.items():运行时,您会立即从中返回。

试试这个版本:

import os

def calc_avg(num_list):
    return round(sum (num_list) / len(num_list))

def directory_summary(a_dir):

  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:'

  for file in mydir:
    fileext = os.path.splitext(file)[1]
    filesz = os.path.getsize(file)
    filedict.setdefault(fileext,[]).append(filesz)


  return_values = []
  for ext, sz in filedict.items():
    values = (ext_str+ext,
              cnt_str,
              str(len(sz)),
              max_str,
              str(max(sz)),
              min_str,
              str(min(sz)),
              avg_str,
              str(calc_avg(sz)))
  return return_values

myd = r'C:\GIS'

print ('Summary of {0} contents:'.format(myd))
results = directory_summary(myd)
for i in results:
    print(i)
于 2013-09-21T15:39:21.917 回答