"""
找到任意目录树里所有给定类型中的最大的那个
避免重复路径,捕获错误,添加追踪和行数大小。
同样使用集合,文件迭代器和生成器以避免装载
整个文件,并试图绕过不可解码的目录/文件名称
的打印。
"""
import os,pprint
from sys import argv,exc_info
#0代表关闭,1代表目录,2代表加上文件
trace=1
dirname,extname=os.curdir,'.py'
if len(argv)>1: dirname=argv[1]
if len(argv)>2: extname=argv[2]
if len(argv)>3: trace=int(argv[3])
def tryprint(arg):
try:
#不能打印的文件名
print(arg)
except UnicodeEncodeError:
print(arg.encode())
visited=set()
allsizes=[]
for (Dir,SubDir,Files) in os.walk(dirname):
if trace: tryprint(Dir)
Dir=os.path.normpath(Dir)
fixname=os.path.normcase(Dir)
if fixname in visited:
if trace: tryprint('....skipping...',Dir)
else:
visited.add(fixname)
for filename in Files:
if filename.endswith(extname):
if trace > 1: tryprint(filename)
fullname=os.path.join(Dir,filename)
try:
bytesize=os.path.getsize(fullname)
linesize=sum(+1 for line in open(fullname,'rb'))
except Exception:
print('error',exc_info()[0])
else:
allsizes.append((bytesize,linesize,fullname))
for (title,key) in [('bytes',0),('lines',1)]:
print('\\nBy %s...' % title)
allsizes.sort(key=lambda x: x[key])
pprint.pprint(allsizes[:3])
pprint.pprint(allsizes[-3:])