基於Python獲取資料夾中檔案數量與其子資料夾中檔案數量
阿新 • • 發佈:2021-05-14
最近,需要對多個資料夾統計其內部檔案數量。其中,這多個需要統計檔案數量的資料夾都放在一個總資料夾內。
這一操作基於Python來實現是非常方便、快捷的。話不多說,我們對相關的Python程式碼來進行詳細介紹。
import os
target_path='H:/2020/'
all_content=os.listdir(target_path)
print('All content numbers is',len(all_content))
count_num=1
for content in all_content:
if os.path.isdir(target_path+content) :
all_sub_content=os.listdir(target_path+content)
if len(all_sub_content)!=361:
print(count_num,content,'sub content number is',len(all_sub_content))
count_num=count_num+1
可以看到,程式碼是非常非常簡潔的。
首先,target_path
是我們的總資料夾路徑,用os.listdir
來獲取總資料夾下面的全部內容(包括檔案與子資料夾),並列印總資料夾
if
判斷與isdir
函式來獲取總資料夾下的全部子資料夾,並對子資料夾依次利用同樣的方式來獲取其內部檔案的數量,並打印出來。
其中,上述程式碼的以下部分:
if len(all_sub_content)!=480:
print(count_num,content,'sub content number is',len(all_sub_content))
count_num=count_num+1
是我為了方便,直接對不滿足檔案個數為480
的子資料夾加以篩選,從而只輸出文件個數非480
if
判斷語句去掉就可以啦~
最後,可以看到上述程式碼我是直接將結果打印出來的;如果實際情況中檔案或資料夾數量很多,大家需要將結果輸出到.csv
等Excel檔案中的話,可以直接參考這篇部落格(https://blog.csdn.net/zhebushibiaoshifu/article/details/114001720)的2.9部分,這裡就不再贅述。
歡迎關注CSDN/公眾號/知乎/微博:瘋狂學習GIS