您的位置:首页 > 编程语言 > Python开发

用PYTHON实现将电脑里的所有文件按大小排序,便于清理

2014-06-08 22:45 477 查看
嘿嘿,慢慢找到写代码的感觉了。

这个小程序涉及的东东还是很多的,数据结构的设计,错误的处理,快速字典排序,文件数值调整。。。。

import os,os.path
import glob

SUFFIXES = ['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 = 0
fileDict = {}
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'


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐