当前位置: 首页 > news >正文

清理C盘的python脚本

前提条件

回收站清理需要安装 winshell 库

命令:pip install winshell

执行命令:

将代码保存为xx.py文件 找到脚本文件所在目录,执行命令:python xx.py

清理的文件夹和文件类型
1. 下载文件夹 (cleanup_downloads())
- 位置:用户下载文件夹( Downloads 或 下载 )
- 清理对象:
- 临时文件: *.tmp , *.temp
- 日志文件: *.log
- 备份文件: *.bak
- 浏览器下载临时文件: *.crdownload , *.partial , *.download
2. ModelScope 缓存 (cleanup_modelscope_cache())
- 位置:
- ~/.cache/modelscope (主要缓存目录)
- ~/AppData/Local/modelscope
- ~/.modelscope
- 清理对象:
- 已下载的模型文件(如 Wan2.2-T2V-A14B 模型)
- 所有 ModelScope SDK 缓存的文件
3. Python 缓存 (cleanup_python_cache())
- 位置:
- pip 缓存: ~/AppData/Local/pip/cache
- conda 缓存(如果安装了 conda): ~/AppData/Local/conda/conda/pkgs
- 清理对象:
- Python 包安装缓存
4. 系统临时文件 (cleanup_temp_files())
- 位置:系统临时文件夹( tempfile.gettempdir() )
- 清理对象:所有临时文件和文件夹
5. 用户临时文件 (cleanup_user_temp_files())
- 位置: ~/AppData/Local/Temp
- 清理对象:用户级别的临时文件和文件夹
6. 浏览器缓存 (cleanup_browser_cache())
- 位置:
- Chrome 浏览器缓存: ~/AppData/Local/Google/Chrome/User Data/Default/Cache
- Edge 浏览器缓存: ~/AppData/Local/Microsoft/Edge/User Data/Default/Cache
- 清理对象:浏览器缓存文件
7. Windows 更新缓存 (cleanup_windows_update_cache())
- 位置: C:\Windows\SoftwareDistribution\Download
- 清理对象:Windows 系统更新过程中下载的临时文件
8. Windows 错误报告文件 (cleanup_error_reports())
- 位置: ~/AppData/Local/Microsoft/Windows/WER
- 清理对象:系统错误报告文件
9. 系统日志文件 (cleanup_system_logs())
- 位置: C:\Windows\System32\winevt\Logs
- 清理对象:Windows 系统事件日志文件( *.evtx )
10. 回收站 (cleanup_recycle_bin())
- 需要安装 winshell 库
- 清理对象:回收站中的所有文件

示例代码:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

"""

C盘空间清理脚本

用于清理下载文件夹、缓存文件夹、已下载的模型及垃圾文件

"""

import os

import shutil

import sys

import tempfile

import glob


def get_user_profile():

"""获取当前用户的Profile目录"""

if sys.platform.startswith('win32'):

return os.environ.get('USERPROFILE', os.path.expanduser('~'))

return os.path.expanduser('~')


def cleanup_downloads():

"""清理下载文件夹"""

print("清理下载文件夹...")

try:

# 用户下载文件夹

download_dirs = [

os.path.join(get_user_profile(), 'Downloads'),

os.path.join(get_user_profile(), '下载')

]

for download_dir in download_dirs:

if os.path.exists(download_dir):

print(f"检查文件夹: {download_dir}")

# 可以添加要清理的特定文件类型

extensions_to_remove = [

'*.tmp', '*.temp', '*.log', '*.bak',

'*.crdownload', '*.partial', '*.download'

]

for ext in extensions_to_remove:

pattern = os.path.join(download_dir, ext)

for file_path in glob.glob(pattern):

try:

os.remove(file_path)

print(f"删除临时文件: {os.path.basename(file_path)}")

except Exception as e:

print(f"无法删除 {file_path}: {e}")

return True

except Exception as e:

print(f"清理下载文件夹失败: {e}")

return False


def cleanup_modelscope_cache():

"""清理ModelScope缓存"""

print("\n清理ModelScope缓存...")

try:

cache_dirs = [

os.path.join(get_user_profile(), '.cache', 'modelscope'),

os.path.join(get_user_profile(), 'AppData', 'Local', 'modelscope'),

os.path.join(get_user_profile(), '.modelscope')

]

removed_size = 0

for cache_dir in cache_dirs:

if os.path.exists(cache_dir):

print(f"检查ModelScope缓存: {cache_dir}")

# 获取缓存目录大小

total_size = 0

for dirpath, dirnames, filenames in os.walk(cache_dir):

for f in filenames:

fp = os.path.join(dirpath, f)

total_size += os.path.getsize(fp)

if total_size > 0:

try:

shutil.rmtree(cache_dir)

removed_size += total_size

print(f"删除了 {format_size(total_size)} 的ModelScope缓存")

except Exception as e:

print(f"无法删除ModelScope缓存 {cache_dir}: {e}")

return removed_size

except Exception as e:

print(f"清理ModelScope缓存失败: {e}")

return 0


def cleanup_python_cache():

"""清理Python缓存"""

print("\n清理Python缓存...")

try:

removed_size = 0

# 清理pip缓存

pip_cache_dir = os.path.join(get_user_profile(), 'AppData', 'Local', 'pip', 'cache')

if os.path.exists(pip_cache_dir):

total_size = get_dir_size(pip_cache_dir)

shutil.rmtree(pip_cache_dir)

removed_size += total_size

print(f"删除了 {format_size(total_size)} 的pip缓存")

# 清理conda缓存(如果安装了conda)

conda_cache_dir = os.path.join(get_user_profile(), 'AppData', 'Local', 'conda', 'conda', 'pkgs')

if os.path.exists(conda_cache_dir):

total_size = get_dir_size(conda_cache_dir)

shutil.rmtree(conda_cache_dir)

removed_size += total_size

print(f"删除了 {format_size(total_size)} 的conda缓存")

return removed_size

except Exception as e:

print(f"清理Python缓存失败: {e}")

return 0


def cleanup_temp_files():

"""清理临时文件"""

print("\n清理临时文件...")

try:

removed_size = 0

# 系统临时文件夹

temp_dir = tempfile.gettempdir()

if os.path.exists(temp_dir):

temp_files = glob.glob(os.path.join(temp_dir, '*'))

for temp_file in temp_files:

try:

if os.path.isfile(temp_file):

file_size = os.path.getsize(temp_file)

os.remove(temp_file)

removed_size += file_size

elif os.path.isdir(temp_file):

dir_size = get_dir_size(temp_file)

shutil.rmtree(temp_file)

removed_size += dir_size

except Exception:

pass # 忽略无法删除的临时文件

print(f"删除了 {format_size(removed_size)} 的临时文件")

return removed_size

except Exception as e:

print(f"清理临时文件失败: {e}")

return 0


def cleanup_browser_cache():

"""清理浏览器缓存"""

print("\n清理浏览器缓存...")

try:

removed_size = 0

# Chrome浏览器缓存

chrome_cache_dir = os.path.join(get_user_profile(), 'AppData', 'Local', 'Google', 'Chrome', 'User Data', 'Default', 'Cache')

if os.path.exists(chrome_cache_dir):

try:

size = get_dir_size(chrome_cache_dir)

shutil.rmtree(chrome_cache_dir)

os.mkdir(chrome_cache_dir)

removed_size += size

print(f"删除了 {format_size(size)} 的Chrome浏览器缓存")

except Exception as e:

print(f"无法清理Chrome浏览器缓存: {e}")

# Edge浏览器缓存

edge_cache_dir = os.path.join(get_user_profile(), 'AppData', 'Local', 'Microsoft', 'Edge', 'User Data', 'Default', 'Cache')

if os.path.exists(edge_cache_dir):

try:

size = get_dir_size(edge_cache_dir)

shutil.rmtree(edge_cache_dir)

os.mkdir(edge_cache_dir)

removed_size += size

print(f"删除了 {format_size(size)} 的Edge浏览器缓存")

except Exception as e:

print(f"无法清理Edge浏览器缓存: {e}")

return removed_size

except Exception as e:

print(f"清理浏览器缓存失败: {e}")

return 0


def get_dir_size(dir_path):

"""获取目录大小"""

total_size = 0

try:

for dirpath, dirnames, filenames in os.walk(dir_path):

for f in filenames:

fp = os.path.join(dirpath, f)

if os.path.exists(fp):

total_size += os.path.getsize(fp)

except Exception:

pass

return total_size


def format_size(size_bytes):

"""格式化文件大小"""

if size_bytes == 0:

return "0 Bytes"

units = ["B", "KB", "MB", "GB", "TB"]

i = 0

while size_bytes >= 1024 and i < len(units)-1:

size_bytes /= 1024.0

i += 1

return f"{size_bytes:.1f} {units[i]}"


def cleanup_windows_update_cache():

"""清理Windows更新缓存"""

print("\n清理Windows更新缓存...")

try:

removed_size = 0

# Windows更新缓存目录

update_cache_dir = os.path.join(os.environ.get('WINDIR', 'C:\\Windows'), 'SoftwareDistribution', 'Download')

if os.path.exists(update_cache_dir):

total_size = get_dir_size(update_cache_dir)

if total_size > 0:

try:

shutil.rmtree(update_cache_dir)

os.mkdir(update_cache_dir)

removed_size += total_size

print(f"删除了 {format_size(total_size)} 的Windows更新缓存")

except Exception as e:

print(f"无法清理Windows更新缓存: {e}")

return removed_size

except Exception as e:

print(f"清理Windows更新缓存失败: {e}")

return 0


def cleanup_recycle_bin():

"""清理回收站(需要管理员权限)"""

print("\n清理回收站...")

try:

import winshell

if winshell.recycle_bin().count() > 0:

# 获取回收站大小

total_size = 0

for item in winshell.recycle_bin():

total_size += item.size

# 清空回收站

winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)

print(f"删除了 {format_size(total_size)} 的回收站内容")

return total_size

else:

print("回收站为空")

return 0

except ImportError:

print("未找到 winshell 库,无法清理回收站")

return 0

except Exception as e:

print(f"清理回收站失败: {e}")

return 0


def cleanup_system_logs():

"""清理系统日志文件"""

print("\n清理系统日志文件...")

try:

removed_size = 0

# Windows系统日志目录

log_dir = os.path.join(os.environ.get('WINDIR', 'C:\\Windows'), 'System32', 'winevt', 'Logs')

if os.path.exists(log_dir):

log_files = glob.glob(os.path.join(log_dir, '*.evtx'))

for log_file in log_files:

try:

file_size = os.path.getsize(log_file)

# 系统日志文件通常需要管理员权限才能删除,这里尝试重命名后删除

temp_name = log_file + ".old"

os.rename(log_file, temp_name)

os.remove(temp_name)

removed_size += file_size

print(f"删除了日志文件: {os.path.basename(log_file)} ({format_size(file_size)})")

except Exception as e:

print(f"无法删除日志文件 {os.path.basename(log_file)}: {e}")

return removed_size

except Exception as e:

print(f"清理系统日志文件失败: {e}")

return 0


def cleanup_error_reports():

"""清理Windows错误报告文件"""

print("\n清理Windows错误报告文件...")

try:

removed_size = 0

# Windows错误报告目录

error_report_dir = os.path.join(get_user_profile(), 'AppData', 'Local', 'Microsoft', 'Windows', 'WER')

if os.path.exists(error_report_dir):

for root, dirs, files in os.walk(error_report_dir):

for file in files:

file_path = os.path.join(root, file)

try:

file_size = os.path.getsize(file_path)

os.remove(file_path)

removed_size += file_size

except Exception:

pass

for dir_name in dirs:

dir_path = os.path.join(root, dir_name)

try:

dir_size = get_dir_size(dir_path)

shutil.rmtree(dir_path)

removed_size += dir_size

except Exception:

pass

if removed_size > 0:

print(f"删除了 {format_size(removed_size)} 的Windows错误报告文件")

else:

print("未找到可清理的错误报告文件")

return removed_size

except Exception as e:

print(f"清理Windows错误报告文件失败: {e}")

return 0


def cleanup_user_temp_files():

"""清理用户临时文件目录"""

print("\n清理用户临时文件目录...")

try:

removed_size = 0

# 用户临时文件夹

user_temp_dir = os.path.join(get_user_profile(), 'AppData', 'Local', 'Temp')

if os.path.exists(user_temp_dir):

temp_files = glob.glob(os.path.join(user_temp_dir, '*'))

for temp_file in temp_files:

try:

if os.path.isfile(temp_file):

file_size = os.path.getsize(temp_file)

os.remove(temp_file)

removed_size += file_size

elif os.path.isdir(temp_file):

dir_size = get_dir_size(temp_file)

shutil.rmtree(temp_file)

removed_size += dir_size

except Exception:

pass

print(f"删除了 {format_size(removed_size)} 的用户临时文件")

return removed_size

except Exception as e:

print(f"清理用户临时文件目录失败: {e}")

return 0


def main():

print("=" * 60)

print("C盘空间清理脚本")

print("=" * 60)

total_removed = 0

# 清理下载文件夹

if cleanup_downloads():

pass

else:

print("下载文件夹清理失败")

# 清理ModelScope缓存

modelscope_size = cleanup_modelscope_cache()

total_removed += modelscope_size

# 清理Python缓存

python_cache_size = cleanup_python_cache()

total_removed += python_cache_size

# 清理临时文件

temp_file_size = cleanup_temp_files()

total_removed += temp_file_size

# 清理用户临时文件目录

user_temp_size = cleanup_user_temp_files()

total_removed += user_temp_size

# 清理浏览器缓存

browser_cache_size = cleanup_browser_cache()

total_removed += browser_cache_size

# 清理Windows更新缓存

windows_update_size = cleanup_windows_update_cache()

total_removed += windows_update_size

# 清理Windows错误报告文件

error_report_size = cleanup_error_reports()

total_removed += error_report_size

# 清理系统日志文件

system_log_size = cleanup_system_logs()

total_removed += system_log_size

# 清理回收站(需要管理员权限)

recycle_bin_size = cleanup_recycle_bin()

total_removed += recycle_bin_size

print("\n" + "=" * 60)

print("清理完成!")

print("=" * 60)

print(f"总共释放空间: {format_size(total_removed)}")

print("\n建议:")

print("- 定期运行此清理脚本")

print("- 删除不再需要的大型安装文件")

print("- 清理系统更新遗留文件")

print("- 检查并清理回收站")

print("- 禁用不需要的启动程序")

return 0


if __name__ == "__main__":

try:

exit_code = main()

sys.exit(exit_code)

except KeyboardInterrupt:

print("\n\n✗ 清理操作被用户中断")

sys.exit(1)

http://www.gsyq.cn/news/188769.html

相关文章:

  • 我的本地知识库初体验
  • 主机设备实时控制 -SFTW-PC-Peripherals
  • 探索Matlab/Simulink中风储联合调频的实际系统应用
  • 多核并行优化与 多核心绑定 实践-SFTW-CPU
  • 洞察先机!提示工程架构师解读Agentic AI技术创新应用先机
  • 作业:打印乘法表
  • 2025年高性能音频传输模块选购指南与应用方案推荐
  • 机器学习领袖谈AI普及与多元化发展
  • 基于深度学习的杂草检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
  • Tauri框架入门:基本概念与快速使用指南
  • 邮件错发怎么办 撤回防泄密关键一步!
  • 让系统“杀不死”:同步与异步场景下的弹性设计模式手册
  • Hive与HBase深度对比:大数据存储与查询的最佳实践
  • 开源推荐--RustDesk:基于Rust的远程桌面神器,彻底告别TeamViewer/AnyDesk!
  • scimed函数发布,轻松完成中介分析
  • vue大学生健身爱好者交流网站的设计与实现
  • YOLOv8 GFL广义交并比损失函数应用
  • FOFA技术结合YOLOv8实现网络空间图像资产识别新方案
  • YOLOv8模型部署最佳实践:基于Docker Run的容器化方案
  • 《程序员修炼之道》笔记七
  • fiddler中的cookies详解
  • 深度解码语义搜索:从Google蜂鸟算法到实体建模的SEO演进
  • YOLOv8 ShuffleNet V2高速推理适配尝试
  • YOLOv8项目实战:在/root/ultralytics目录下运行第一个demo
  • YOLOv8 SwAV聚类引导的预训练方法
  • YOLOv8目标检测全流程:从Git下载到模型训练详解
  • YOLOv8 Mask RCNN风格实例分割扩展
  • YOLOv8 Virtual Adversarial Training对抗扰动生成
  • 深度探讨:随着 LLM 推理能力的指数级提升,LangChain 这类编排框架是否会被整合进模型内部?
  • YOLOv8 DCNv2在YOLOv8中的适用性评估