遍歷本地文件系統 (sys, os, path),例如寫一個程序統計一個目錄下所有文件大小并按各種條件排序并保存結果,代碼如下:
#coding:GBKimport os;def SortList(item): return item[1];def ReadSize(fileName): return float(os.path.getsize(fileName));def WriteAll(path): l = [] loger = open("test.log","w"); writer = open("path.txt","w"); reader = open("path.txt","r"); size = 0; for root,dirs,files in os.walk(path): for filesPath in files: try: fllePath = os.path.join(root,filesPath); fileSize = float(ReadSize(fllePath)/1024); size += fileSize; x = (fllePath,int(fileSize)); l.append(x); except: loger.write("讀取:"+os.path.join(root,filesPath)+"文件大小失敗!/n"); continue; l = sorted(l,key=SortList,reverse=True); for item in l: strTmp = ""; if float(item[1]/1024) > 1024: strTmp = item[0]+" "+str(int(float(item[1]/1024/1024)))+"GB/n"; elif item[1] > 1024: strTmp = item[0]+" "+str(int(float(item[1]/1024)))+"MB/n"; else: strTmp = item[0]+" "+str(item[1])+"KB/n"; writer.write(strTmp); writer.write("共使用磁盤空間:"+str(float(size/1024))+"MB"); loger.close(); writer.close(); PRint(reader.read()); reader.close();fileName = os.getcwd();WriteAll(fileName);raw_input("END...");
新聞熱點
疑難解答