当文件数量太多时,就
IndexError: list index out of range。。。。。
import os from os.path import join,getsize def formatsize(bytes): try: bytes = float(bytes) kb = bytes / 1024 except Exception as e: print("wrong format string") return "error" if kb>1024: M=kb/1024 if M>1024: G=M/1024 return "%.2fG" %(G) else: return "%.2fM" %(M) else: return "%.2fkb" %(kb) l={} for root,dirs,files in os.walk(r"C:UsersjzhangDownloads"): for file in files: file1=join(root,file) # print(file1,getsize(file1)) l[file]=getsize(file1) print(len(l)) k=sorted(l.items(),key=lambda l:l[1],reverse=True) for i in range(0,10): # print(k[i][0],k[i][1]) print(k[i][0],formatsize(k[i][1]))