背景需求
有时候电脑里磁盘空间越来越小,不得不删除一些占空间大的文件。最笨的方法就是对某一个文件夹下一个一个查看大小,效率太慢。
效果图
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)