Python之練習Demo

來源:互聯網
上載者:User

標籤:

遍曆本地檔案系統 (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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.