相信平日里很多人都有一个非常头疼的问题,那就是C盘的存储问题,随着自己电脑的使用时间的增长,不管平日里如何保养自己的C盘内存空间,都会出现内存不够用的情况,但是自己使用windows自带的清理系统或者360清理、系统盘瘦身、腾讯管家等等清理软件依然没有什么用,明明C盘只剩几个G的空间了,但是清理软件就是不能够成功地将那些垃圾清理干净,每次只能够清理个几个g的空间,之后就是完全清不动了,所以今天笔者分享一段python代码来解决这个问题,方便大家之后能够顺利解决C盘的存储空间被占满的问题。
相关的python代码如下:
import os
import shutil
import time
def scan_c_drive():
"""扫描C盘的垃圾文件"""
c_drive = "C:\\"
temp_files = []
cache_files = []
log_files = []
total_files_scanned = 0
for root, dirs, files in os.walk(c_drive):
for file in files:
total_files_scanned += 1
if total_files_scanned % 1000 == 0: # 每扫描1000个文件更新一次进度
print(f"已扫描 {total_files_scanned} 个文件...")
if file.endswith(".tmp") or file.endswith(".temp"):
temp_files.append(os.path.join(root, file))
elif file.endswith(".log"):
log_files.append(os.path.join(root, file))
elif "cache" in root.lower(): # 检查文件路径中是否包含"cache"
cache_files.append(os.path.join(root, file))
print(f"扫描完成,共处理 {total_files_scanned} 个文件。")
return temp_files, cache_files, log_files
def delete_files(file_list):
"""删除提供的文件列表"""
deleted_count = 0
failed_count = 0
total_files = len(file_list)
for index, file in enumerate(file_list):
try:
if os.path.exists(file):
os.remove(file)
deleted_count += 1
# 实时进度反馈
if (index + 1) % 50 == 0 or (index + 1) == total_files:
print(f"已处理 {index + 1}/{total_files} 个文件... ({deleted_count} 成功, {failed_count} 失败)")
except Exception as e:
failed_count += 1
# 输出错误信息但不中断程序
print(f"删除失败 {file}: {str(e)}")
if (index + 1) % 50 == 0 or (index + 1) == total_files:
print(f"已处理 {index + 1}/{total_files} 个文件... ({deleted_count} 成功, {failed_count} 失败)")
time.sleep(0.01) # 模拟实际操作的时间消耗
return deleted_count, failed_count
if __name__ == "__main__":
print("开始扫描磁盘...")
temp_files, cache_files, log_files = scan_c_drive()
total_files = len(temp_files) + len(cache_files) + len(log_files)
print(f"总共找到 {total_files} 个可能的垃圾文件。")
user_input = input("是否删除所有找到的垃圾文件? (y/n): ")
if user_input.lower() == 'y':
print("开始删除文件...")
deleted_temp, failed_temp = delete_files(temp_files)
deleted_cache, failed_cache = delete_files(cache_files)
deleted_log, failed_log = delete_files(log_files)
total_deleted = deleted_temp + deleted_cache + deleted_log
total_failed = failed_temp + failed_cache + failed_log
print(f"清理完成:总共删除 {total_deleted} 个文件,{total_failed} 个文件删除失败。")
else:
print("操作已取消。")
在python中运行上面的代码之后,接下来就是静静地等待程序的清理了。
成功清理清理就会出现上图所示的提示。如果出现下面的提示,那么就说明程序需要获得管理员权限或者关闭相应的服务才能够清理。