1. 程式人生 > >python 統計資料夾,檔案數目

python 統計資料夾,檔案數目

import os
dirnum = 0
filenum = 0
path = '目標資料夾路徑'

for lists in os.listdir(path):
    sub_path = os.path.join(path, lists)
    print(sub_path)
    if os.path.isfile(sub_path):
        filenum = filenum+1
    elif os.path.isdir(sub_path):
        dirnum = dirnum+1

print('dirnum: ',dirnum)
print('filenum: ',filenum)

"""或者快速輸出資料夾和檔案數目"""
path = '目標資料夾路徑'
print('dirnum:',len([lists for lists in os.listdir(path) if os.path.isdir(os.path.join(path, lists))]))
print('filenum:',len([lists for lists in os.listdir(path) if os.path.isfile(os.path.join(path, lists))]))

os.listdir(dirname):列出dirname下的目錄和檔案 
os.getcwd():獲得當前工作目錄 
os.curdir:返回當前目錄(’.’) 
os.chdir(dirname):改變工作目錄到dirname 
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就返回false 
os.path.isfile(name):判斷name是不是一個檔案,不存在name也返回false 
os.path.exists(name):判斷是否存在檔案或目錄name 
os.path.getsize(name):獲得檔案大小,如果name是目錄返回0 
os.path.abspath(name):獲得絕對路徑 
os.path.normpath(path):規範path字串形式 
os.path.split(name):分割檔名與目錄(事實上,如果你完全使用目錄,它也會將最後一個目錄作為檔名而分離,同時它不會判斷檔案或目錄是否存在) 
os.path.splitext():分離檔名與副檔名 
os.path.join(path,name):連線目錄與檔名或目錄 
os.path.basename(path):返回檔名 
os.path.dirname(path):返回檔案路徑