做window开发时有时候电脑爬着很多程序,需要查看文件的数量和大小,所以用python的os模块写个小代码,计算后在数量多时能省四分之一的时间。

import os
import time


def get_file_num(path):
    global total_size, num_total, file_num
    # path = r"E:\004_kongfuz_selenium70_120W"
    os.chdir(path)
    ret = os.listdir()
    # os.getcwd()
    print(ret)
    print(os.getcwd())
    current_path = os.getcwd()
    for i in ret:
        path1 = os.path.join(current_path, i)
        a = os.path.isdir(path1)
        if a:
            get_file_num(path1)
        else:
            file_num += 1
            total_size += os.path.getsize(path1)
    num_total += len(ret)


if __name__ == '__main__':
    start_time = time.time()
    total_size = 0
    num_total = 0
    file_num = 0
    path = r"E:\004_kongfuz_selenium70_120W"
    get_file_num(path)
    end_time = time.time()
    print("用时", end_time - start_time)
    print("总大小", total_size / 1024 / 1024)
    print("总文件夹+文件", num_total)
    print("总文件", file_num)