我正在尝试编写一个脚本,它将遍历我的目录和子目录,并列出特定大小的文件数。例如0kb-1kb:3、1kb-4kb:4、4-16KB:4、16KB-64-kb:11,并以4的倍数继续。我能够得到文件编号的列表,大小在人类可读的格式,并找到一个大小组中的文件数。但我觉得我的代码非常混乱,与标准不符。需要帮助重新编写代码吗
import os
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
route = raw_input('Enter a location')
def human_Readable(nbytes):
if nbytes == 0: return '0 B'
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i])
def file_Dist(path, start,end):
counter = 0
counter2 = 0
for path, subdir, files in os.walk(path):
for r in files:
if os.path.getsize(os.path.join(path,r)) > start and os.path.getsize(os.path.join(path,r)) < end:
counter += 1
#print "Number of files less than %s:" %(human_Readable(end)), counter
print "Number of files greater than %s less than %s:" %(human_Readable(start), human_Readable(end)), counter
file_Dist(route, 0, 1024)
file_Dist(route,1024,4095)
file_Dist(route, 4096, 16383)
file_Dist(route, 16384, 65535)
file_Dist(route, 65536, 262143)
file_Dist(route, 262144, 1048576)
file_Dist(route, 1048577, 4194304)
file_Dist(route, 4194305, 16777216)
这里有一些改进的建议。在
os.path.getsize()
对于断开的符号链接失败;我将使用os.lstat().st_size
,这将生成正确的链接文件树大小。在这是一个执行上述建议的程序版本。注意,它仍然忽略大小为16mib以上的文件-这也可以改进。在
我认为行
^{pr2}$group = (math.frexp(size/1024)[1]+1)/2
,它产生与size
对应的counter list元素的索引,需要一些解释。考虑我们得到了这样一个画面:通过选取大小的浮点表示的基2指数并对其进行一点调整(},以及{}从基数2转换为基数4)我们可以计算出适当的计数器列表索引。在
+1
因为尾数在[0.5, 1[
而不是{相关问题 更多 >
编程相关推荐