Python_計算檔案夾大小

來源:互聯網
上載者:User

標籤:子目錄   絕對路徑   列印   python   結束   print   app   os.path   end   

計算檔案夾大小

 

os.listdir(‘dirname‘)    列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印

os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略

os.path.getsize(path) 返回path的大小

os.path.isdir(path)  如果path是一個存在的目錄,則返回True。否則返回False
遞迴版:
 1 import os 2  3  4 def get_size(path): 5     ret = os.listdir(path) 6     print(ret) 7     total = 0 8  9     for name in ret:10         abs_path = os.path.join(path, name)11 12         if os.path.isdir(abs_path):13             total += get_size(abs_path)14         else:15             total += os.path.get.size(abs_path)16 17     return total18 19 path = r‘D:\S12\py筆記‘20 ret = get_size(path)21 print(ret)

 

 

  遞迴什麼時候結束?  傳回值的時候結束遞迴.

 

堆棧

  棧是一種電腦儲存資料的思想:先進後出

 

壓棧思想:

 1 import os 2  3  4 path = r‘D:\S12\py筆記\day19‘ 5 dir_lst = [path] 6  7 while dir_list: 8     path = dir_lst.pop() 9     ret = os.listdir(path)10 11     for name in ret:12         abs_path = os.path.join(path, name)13     14         if os.path.isdir(abs_path):15             dir_lst.append(abs_path)16         else:17             total += os.path.getsize(abs_path)18 19 print(total)

 

Python_計算檔案夾大小

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.