Calculate and display the size of the specified folder

background needs

Sometimes the disk space in the computer is getting smaller and smaller, and some files that take up a lot of space have to be deleted. The most stupid way is to check the size of a certain folder one by one, which is too slow.

renderings

insert image description here
insert image description here

Code

import os
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'sans-serif'  # 设置字体为无衬线字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置使用SimHei字体(中文的衬线字体)

plt.rcParams['font.size'] = 12
plt.rcParams['axes.linewidth'] = 1.5
plt.rcParams['axes.grid'] = True
def get_folder_size(folder):
    total_size = 0
    for root, dirs, files in os.walk(folder):
        for file in files:
            file_path = os.path.join(root, file)
            total_size += os.path.getsize(file_path)
    return total_size / (1024 * 1024)  # 转换为MB

def get_folder_sizes(directory):
    folder_sizes = {
    
    }
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        if os.path.isdir(item_path):
            folder_size = get_folder_size(item_path)
            folder_sizes[item] = folder_size
    return folder_sizes

def plot_bar_chart(folder_sizes):
    folders, sizes = zip(*folder_sizes.items())
    colors = plt.cm.tab20c(range(len(folders)))
    plt.figure(figsize=(10, 6))
    plt.bar(folders, sizes, color=colors)
    plt.xlabel('Folders')
    plt.ylabel('Size (MB)')
    plt.title('Folder Sizes')
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.show()

def plot_pie_chart(folder_sizes):
    folders, sizes = zip(*folder_sizes.items())
    plt.figure(figsize=(8, 8))
    plt.pie(sizes, labels=folders, autopct='%1.1f%%', startangle=140)
    plt.title('Folder Size Distribution')
    plt.axis('equal')
    plt.show()

if __name__ == "__main__":
    # current_directory = os.getcwd()
    target_directory = r"D:\A计算机学习文件夹"  
    folder_sizes = get_folder_sizes(target_directory)

    for folder, size in folder_sizes.items():
        print(f"{
      
      folder}: {
      
      size:.2f} MB")

    plot_bar_chart(folder_sizes)
    plot_pie_chart(folder_sizes)


Guess you like

Origin blog.csdn.net/qq_41661809/article/details/131995142