嘿嘿,慢慢找到写代码的感觉了。
这个小程序涉及的东东还是很多的,数据结构的设计,错误的处理,快速字典排序,文件数值调整。。。。
import os,os.pathimport globSUFFIXES = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']def approximate_size(size): '''Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes Returns: string ''' if size < 0: raise ValueError('number must be non-negative') multiple = 1024.0 for suffix in SUFFIXES: size /= multiple if size < multiple: return '{0:.1f} {1}'.format(size, suffix)rootDir = raw_input('Please input root dir:')count = 0fileDict = {}sortfileDict = {}for parent, dirnames, filenames in os.walk(rootDir): #print('Folder: %s' % dirName) for filename in filenames: name = os.path.join(parent,filename) try: filesize = os.path.getsize(name) except (OSError): filesize = 0 fileDict[name] = filesize count += 1 print count sortfileDict = sorted(fileDict.iteritems(), key=lambda fileDict:fileDict[1], reverse = True)fList = open('filelist.txt','w')for i in range(len(sortfileDict)): #print sortfileDict[i][0], "\t", sortfileDict[i][1] fileList = "{0} \t {1} \n".format(sortfileDict[i][0], approximate_size(sortfileDict[i][1])) fList.write(fileList)fList.close()print 'DONE'