使用Python监控文件夹大小变化
在本文中,我们将学习如何使用Python来监控和记录磁盘上特定文件夹的大小变化。这对于了解磁盘空间使用情况非常有用,特别是在需要定期监控特定目录的大小时。
准备工作
确保已经安装了Python,并熟悉基本的Python编程。
代码实现
我们将编写一个Python脚本,该脚本可以遍历指定目录及其子目录,计算每个目录的大小,并以易读的格式显示结果。
获取目录大小
首先,我们定义一个函数get_directory_size
来获取指定目录的总大小。
查看代码
python
import os
def get_directory_size(directory):
total_size = 0
for path, dirs, files in os.walk(directory):
for f in files:
fp = os.path.join(path, f)
try:
total_size += os.path.getsize(fp)
except FileNotFoundError:
print(f"===> FileNotFoundError: {fp}")
return total_size
格式化文件大小
接下来,我们定义一个函数format_size
来将文件大小格式化为易读的格式。
查看代码
python
def format_size(size):
"""格式化文件大小"""
if size < 1024:
return f"{size} bytes"
elif size < 1024**2:
return f"{size / 1024:.2f} KB"
elif size < 1024**3:
return f"{size / 1024**2:.2f} MB"
else:
return f"{size / 1024**3:.2f} GB"
主程序
在主程序中,我们遍历指定目录,计算每个子目录的大小,并将其显示出来。
查看代码
python
directory_path = r'D:/'
if __name__ == "__main__":
entries = os.listdir(directory_path)
tot = dict()
for directory in entries:
if directory == "$RECYCLE.BIN": continue
directory = os.path.join(directory_path, directory)
size = get_directory_size(directory)
print(f"{directory}: {format_size(size)}")
tot[directory] = [format_size(size), size]
sorted_dict = dict(sorted(tot.items(), key=lambda item: item[1][1], reverse=True))
json_data = json.dumps(sorted_dict, indent=4, ensure_ascii=False)
output_file = r'./2024_5_25的D盘各目录大小.json'
with open(output_file, 'w') as file:
file.write(json_data)
结果展示
运行上述脚本后,在控制台中看到类似以下输出:
同时,脚本还会生成一个JSON文件,其中包含了按大小排序的目录信息。
总结
通过本文,我们学会了如何使用Python来监控和记录文件夹的大小变化。我们可以定期运行此脚本,以跟踪磁盘空间的使用情况。