標籤:
遍曆本地檔案系統 (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...");
Python之練習Demo