清理C盘的python脚本

前提条件

回收站清理需要安装 winshell 库

命令:pip install winshell

执行命令:

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

清理的文件夹和文件类型

  1. 下载文件夹 (cleanup_downloads())
  • 位置:用户下载文件夹( Downloads 或 下载 )

  • 清理对象:

  • 临时文件: *.tmp , *.temp

  • 日志文件: *.log

  • 备份文件: *.bak

  • 浏览器下载临时文件: *.crdownload , *.partial , *.download

  1. ModelScope 缓存 (cleanup_modelscope_cache())
  • 位置:

  • ~/.cache/modelscope (主要缓存目录)

  • ~/AppData/Local/modelscope

  • ~/.modelscope

  • 清理对象:

  • 已下载的模型文件(如 Wan2.2-T2V-A14B 模型)

  • 所有 ModelScope SDK 缓存的文件

  1. Python 缓存 (cleanup_python_cache())
  • 位置:

  • pip 缓存: ~/AppData/Local/pip/cache

  • conda 缓存(如果安装了 conda): ~/AppData/Local/conda/conda/pkgs

  • 清理对象:

  • Python 包安装缓存

  1. 系统临时文件 (cleanup_temp_files())
  • 位置:系统临时文件夹( tempfile.gettempdir() )

  • 清理对象:所有临时文件和文件夹

  1. 用户临时文件 (cleanup_user_temp_files())
  • 位置: ~/AppData/Local/Temp

  • 清理对象:用户级别的临时文件和文件夹

  1. 浏览器缓存 (cleanup_browser_cache())
  • 位置:

  • Chrome 浏览器缓存: ~/AppData/Local/Google/Chrome/User Data/Default/Cache

  • Edge 浏览器缓存: ~/AppData/Local/Microsoft/Edge/User Data/Default/Cache

  • 清理对象:浏览器缓存文件

  1. Windows 更新缓存 (cleanup_windows_update_cache())
  • 位置: C:\Windows\SoftwareDistribution\Download

  • 清理对象:Windows 系统更新过程中下载的临时文件

  1. Windows 错误报告文件 (cleanup_error_reports())
  • 位置: ~/AppData/Local/Microsoft/Windows/WER

  • 清理对象:系统错误报告文件

  1. 系统日志文件 (cleanup_system_logs())
  • 位置: C:\Windows\System32\winevt\Logs

  • 清理对象:Windows 系统事件日志文件( *.evtx )

  1. 回收站 (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)

相关推荐
一只鹿鹿鹿2 小时前
网络信息与数据安全建设方案
大数据·运维·开发语言·网络·mysql
a努力。2 小时前
国家电网Java面试被问:慢查询的优化方案
java·开发语言·面试
AI手记叨叨2 小时前
Python数学:几何运算
python·数学·解析几何·射影几何·微分几何·欧几里得几何
@小码农3 小时前
202512 电子学会 Scratch图形化编程等级考试四级真题(附答案)
java·开发语言·算法
ejjdhdjdjdjdjjsl3 小时前
C#类型转换与异常处理全解析
开发语言·c#
toolhow3 小时前
SelfAttenion自注意力机制
pytorch·python·深度学习
智航GIS3 小时前
6.2 while循环
java·前端·python
qq_336313933 小时前
java基础-IO流(转换流)
java·开发语言·python
小宇的天下3 小时前
Calibre nmDRC 运行机制与规则文件(13-2)
运维·开发语言