遍历本地文件系统 (sys, os, path),例如写一个程序统计一个目录下所有文件大小并按各种条件排序并保存结果,代码如下:
1 #coding:GBK 2 import os; 3 4 def SortList(item): 5 return item[1]; 6 7 def ReadSize(fileName): 8 return float(os.path.getsize(fileName)); 9 10 def WriteAll(path): 11 l = [] 12 loger = open("test.log","w"); 13 writer = open("path.txt","w"); 14 reader = open("path.txt","r"); 15 size = 0; 16 for root,dirs,files in os.walk(path): 17 for filesPath in files: 18 try: 19 fllePath = os.path.join(root,filesPath); 20 fileSize = float(ReadSize(fllePath)/1024); 21 size += fileSize; 22 x = (fllePath,int(fileSize)); 23 l.append(x); 24 except: 25 loger.write("读取:"+os.path.join(root,filesPath)+"文件大小失败!"); 26 continue; 27 l = sorted(l,key=SortList,reverse=True); 28 for item in l: 29 strTmp = ""; 30 if float(item[1]/1024) > 1024: 31 strTmp = item[0]+" "+str(int(float(item[1]/1024/1024)))+"GB\n"; 32 elif item[1] > 1024: 33 strTmp = item[0]+" "+str(int(float(item[1]/1024)))+"MB\n"; 34 else: 35 strTmp = item[0]+" "+str(item[1])+"KB\n"; 36 37 writer.write(strTmp); 38 writer.write("共使用磁盘空间:"+str(float(size/1024))+"MB"); 39 loger.close(); 40 writer.close(); 41 print(reader.read()); 42 reader.close(); 43 44 fileName = os.getcwd(); 45 WriteAll(fileName); 46 raw_input("END...");
时间: 2024-10-28 15:36:24