鱼C论坛

 找回密码
 立即注册
查看: 31|回复: 4

[作品展示] Python内置库做的清理C盘缓存小工具

[复制链接]
发表于 7 小时前 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码如下:
  1. import os
  2. import shutil
  3. import tempfile
  4. import time
  5. import sys
  6. import glob

  7. def safe_clean_temp_files():
  8.     """安全清理临时文件"""
  9.     print("正在安全清理临时文件...")
  10.     temp_dirs = [
  11.         os.path.join(os.environ.get('USERPROFILE', r'C:\Users'), r'AppData\Local\Temp'),
  12.         tempfile.gettempdir()
  13.     ]
  14.    
  15.     for temp_dir in temp_dirs:
  16.         try:
  17.             if os.path.exists(temp_dir):
  18.                 for root, dirs, files in os.walk(temp_dir):
  19.                     for name in files:
  20.                         try:
  21.                             file_path = os.path.join(root, name)
  22.                             # 只删除7天前的临时文件
  23.                             if os.path.getmtime(file_path) < time.time() - 7 * 24 * 3600:
  24.                                 os.remove(file_path)
  25.                         except (PermissionError, OSError):
  26.                             continue
  27.                 print(f"已安全清理: {temp_dir}")
  28.         except Exception as e:
  29.             print(f"清理 {temp_dir} 时出错: {e}")

  30. def clean_recycle_bin_with_confirmation():
  31.     """带确认的清空回收站"""
  32.     print("\n警告: 此操作将永久删除回收站中的所有文件!")
  33.     confirm = input("确定要清空回收站吗? (y/n): ").lower()
  34.     if confirm == 'y':
  35.         try:
  36.             # 使用内置方法模拟清空回收站
  37.             recycle_bin = os.path.join(os.environ.get('SystemDrive', 'C:'), '$Recycle.Bin')
  38.             if os.path.exists(recycle_bin):
  39.                 for item in os.listdir(recycle_bin):
  40.                     item_path = os.path.join(recycle_bin, item)
  41.                     try:
  42.                         if os.path.isdir(item_path):
  43.                             shutil.rmtree(item_path)
  44.                         else:
  45.                             os.remove(item_path)
  46.                     except (PermissionError, OSError):
  47.                         continue
  48.             print("回收站已清空")
  49.         except Exception as e:
  50.             print(f"清空回收站时出错: {e}")
  51.     else:
  52.         print("跳过回收站清理")

  53. def clean_old_files(directory, days=30):
  54.     """清理指定目录中超过指定天数的文件"""
  55.     if not os.path.exists(directory):
  56.         return
  57.    
  58.     cutoff = time.time() - days * 24 * 3600
  59.     for filename in os.listdir(directory):
  60.         filepath = os.path.join(directory, filename)
  61.         try:
  62.             if os.path.getmtime(filepath) < cutoff:
  63.                 if os.path.isfile(filepath):
  64.                     os.remove(filepath)
  65.                 elif os.path.isdir(filepath):
  66.                     shutil.rmtree(filepath)
  67.         except (PermissionError, OSError):
  68.             continue

  69. def safe_clean_downloads():
  70.     """安全清理下载文件夹"""
  71.     print("正在安全清理下载文件夹...")
  72.     downloads_path = os.path.join(os.environ.get('USERPROFILE', r'C:\Users'), 'Downloads')
  73.     clean_old_files(downloads_path, days=30)
  74.     print("下载文件夹已安全清理")

  75. def clean_thumbnail_cache():
  76.     """清理缩略图缓存"""
  77.     print("正在清理缩略图缓存...")
  78.     thumb_cache = os.path.join(os.environ.get('USERPROFILE', r'C:\Users'),
  79.                              r'AppData\Local\Microsoft\Windows\Explorer')
  80.     if os.path.exists(thumb_cache):
  81.         for filename in os.listdir(thumb_cache):
  82.             if filename.startswith('thumbcache_'):
  83.                 try:
  84.                     os.remove(os.path.join(thumb_cache, filename))
  85.                 except (PermissionError, OSError):
  86.                     continue
  87.     print("缩略图缓存已清理")

  88. def get_disk_usage():
  89.     """显示磁盘使用情况"""
  90.     total, used, free = shutil.disk_usage("C:")
  91.     print("\n磁盘空间信息:")
  92.     print(f"总空间: {total // (2**30)} GB")
  93.     print(f"已使用: {used // (2**30)} GB")
  94.     print(f"剩余空间: {free // (2**30)} GB")

  95. def clean_old_browser_cache(days=30):
  96.     """清理超过指定天数的浏览器缓存"""
  97.     appdata_local = os.getenv('LOCALAPPDATA')
  98.     if not appdata_local:
  99.         return
  100.    
  101.     cutoff_time = time.time() - days * 24 * 3600
  102.    
  103.     # Chrome/Edge/Brave缓存文件通常以以下扩展名结尾
  104.     cache_file_patterns = [
  105.         '_*', 'f_*', 'data_*', 'index'
  106.     ]
  107.    
  108.     browser_cache_dirs = [
  109.         os.path.join(appdata_local, 'Google', 'Chrome', 'User Data'),
  110.         os.path.join(appdata_local, 'Microsoft', 'Edge', 'User Data'),
  111.         os.path.join(appdata_local, 'BraveSoftware', 'Brave-Browser', 'User Data')
  112.     ]
  113.    
  114.     for cache_dir in browser_cache_dirs:
  115.         if not os.path.exists(cache_dir):
  116.             continue
  117.             
  118.         # 查找所有Profile的Cache目录
  119.         for profile_dir in glob.glob(os.path.join(cache_dir, '*')):
  120.             cache_path = os.path.join(profile_dir, 'Cache')
  121.             if os.path.exists(cache_path):
  122.                 print(f"正在检查: {cache_path}")
  123.                 for root, _, files in os.walk(cache_path):
  124.                     for file in files:
  125.                         file_path = os.path.join(root, file)
  126.                         try:
  127.                             if os.path.getmtime(file_path) < cutoff_time:
  128.                                 os.remove(file_path)
  129.                         except:
  130.                             continue

  131. def main():
  132.     print("C盘安全清理工具 (仅使用内置库)")
  133.     print("=" * 50)
  134.    
  135.    
  136.     start_time = time.time()
  137.    
  138.     # 执行安全清理操作
  139.     safe_clean_temp_files()
  140.     clean_recycle_bin_with_confirmation()
  141.     safe_clean_downloads()
  142.     clean_thumbnail_cache()
  143.     clean_old_browser_cache()
  144.    
  145.     # 显示清理结果
  146.     get_disk_usage()
  147.    
  148.     end_time = time.time()
  149.     print(f"\n安全清理完成! 耗时: {end_time - start_time:.2f}秒")
  150.     input("按Enter键退出...")

  151. if __name__ == "__main__":
  152.     main()
复制代码
屏幕截图 2025-07-06 131159.png
屏幕截图 2025-07-06 131153.png

评分

参与人数 2荣誉 +3 鱼币 +7 贡献 +3 C币 +3 收起 理由
小甲鱼 + 3 + 3 + 3 + 3 无条件支持楼主!
某一个“天” + 4 能给我的作品评个分吗

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 7 小时前 | 显示全部楼层
以下是针对您提供的清理C盘缓存工具代码的分析和改进建议:

### 主要问题分析
1. **未定义变量**:`temp_dirs` 和 `browser_cache_dirs` 未赋值
2. **潜在风险**:直接删除 `$Recycle.Bin` 可能引发权限问题
3. **浏览器缓存处理**:缺少浏览器缓存路径和文件模式定义
4. **路径兼容性**:部分路径拼接缺少容错处理

### 改进后的完整代码

  1. import os
  2. import shutil
  3. import tempfile
  4. import time
  5. import sys
  6. import glob

  7. def safe_clean_temp_files():
  8.     """安全清理临时文件"""
  9.     print("正在安全清理临时文件...")
  10.     # 定义临时目录列表(补充定义)
  11.     temp_dirs = [
  12.         tempfile.gettempdir(),
  13.         os.path.join(os.environ.get('SystemRoot', 'C:\\Windows'), 'Temp'),
  14.         os.path.join(os.environ['LOCALAPPDATA'], 'Temp')
  15.     ]
  16.    
  17.     for temp_dir in temp_dirs:
  18.         try:
  19.             if os.path.exists(temp_dir):
  20.                 for root, dirs, files in os.walk(temp_dir):
  21.                     for name in files:
  22.                         try:
  23.                             file_path = os.path.join(root, name)
  24.                             # 只删除7天前的临时文件
  25.                             if os.path.getmtime(file_path) < time.time() - 7 * 24 * 3600:
  26.                                 os.remove(file_path)
  27.                         except (PermissionError, OSError):
  28.                             continue
  29.                 print(f"已安全清理: {temp_dir}")
  30.         except Exception as e:
  31.             print(f"清理 {temp_dir} 时出错: {e}")

  32. def clean_recycle_bin_with_confirmation():
  33.     """带确认的清空回收站(改进权限处理)"""
  34.     print("\n警告: 此操作将永久删除回收站中的所有文件!")
  35.     confirm = input("确定要清空回收站吗? (y/n): ").lower()
  36.     if confirm == 'y':
  37.         try:
  38.             # 更安全的回收站路径获取方式
  39.             from win32com.shell import shell, shellcon
  40.             shell.SHEmptyRecycleBin(None, None, 0)
  41.             print("回收站已清空")
  42.         except ImportError:
  43.             print("请安装pywin32模块: pip install pywin32")
  44.         except Exception as e:
  45.             print(f"清空回收站时出错: {e}")
  46.     else:
  47.         print("跳过回收站清理")

  48. def clean_old_files(directory, days=30):
  49.     """清理指定目录中超过指定天数的文件"""
  50.     if not os.path.exists(directory):
  51.         return
  52.    
  53.     cutoff = time.time() - days * 24 * 3600
  54.     for filename in os.listdir(directory):
  55.         filepath = os.path.join(directory, filename)
  56.         try:
  57.             if os.path.getmtime(filepath) < cutoff:
  58.                 if os.path.isfile(filepath):
  59.                     os.remove(filepath)
  60.                 elif os.path.isdir(filepath):
  61.                     shutil.rmtree(filepath)
  62.         except (PermissionError, OSError):
  63.             continue

  64. def safe_clean_downloads():
  65.     """安全清理下载文件夹"""
  66.     print("正在安全清理下载文件夹...")
  67.     downloads_path = os.path.join(
  68.         os.environ.get('USERPROFILE', 'C:\\Users'),
  69.         'Downloads'
  70.     )
  71.     clean_old_files(downloads_path, days=30)
  72.     print("下载文件夹已安全清理")

  73. def clean_thumbnail_cache():
  74.     """清理缩略图缓存"""
  75.     print("正在清理缩略图缓存...")
  76.     thumb_cache = os.path.join(
  77.         os.environ.get('LOCALAPPDATA', 'C:\\Users'),
  78.         'Microsoft\\Windows\\Explorer'
  79.     )
  80.     if os.path.exists(thumb_cache):
  81.         for filename in glob.glob(os.path.join(thumb_cache, 'thumbcache_*.db')):
  82.             try:
  83.                 os.remove(filename)
  84.             except (PermissionError, OSError):
  85.                 continue
  86.     print("缩略图缓存已清理")

  87. def get_disk_usage():
  88.     """显示磁盘使用情况"""
  89.     total, used, free = shutil.disk_usage("C:\")
  90.     print("\n磁盘空间信息:")
  91.     print(f"总空间: {total // (2**30)} GB")
  92.     print(f"已使用: {used // (2**30)} GB")
  93.     print(f"剩余空间: {free // (2**30)} GB")

  94. def clean_old_browser_cache(days=30):
  95.     """清理超过指定天数的浏览器缓存"""
  96.     appdata_local = os.getenv('LOCALAPPDATA')
  97.     if not appdata_local:
  98.         return
  99.    
  100.     # 补充浏览器缓存路径定义
  101.     browser_cache_dirs = [
  102.         os.path.join(appdata_local, 'Google', 'Chrome', 'User Data'),
  103.         os.path.join(appdata_local, 'Microsoft', 'Edge', 'User Data'),
  104.         os.path.join(appdata_local, 'Mozilla', 'Firefox', 'Profiles')
  105.     ]
  106.    
  107.     cutoff_time = time.time() - days * 24 * 3600
  108.    
  109.     for cache_dir in browser_cache_dirs:
  110.         if not os.path.exists(cache_dir):
  111.             continue
  112.             
  113.         # 查找所有Profile的Cache目录
  114.         for profile_dir in glob.glob(os.path.join(cache_dir, '*')):
  115.             cache_path = os.path.join(profile_dir, 'Cache')
  116.             if os.path.exists(cache_path):
  117.                 print(f"正在检查: {cache_path}")
  118.                 for root, _, files in os.walk(cache_path):
  119.                     for file in files:
  120.                         file_path = os.path.join(root, file)
  121.                         try:
  122.                             if os.path.getmtime(file_path) < cutoff_time:
  123.                                 os.remove(file_path)
  124.                         except:
  125.                             continue

  126. def main():
  127.     print("C盘安全清理工具 (仅使用内置库)")
  128.     print("=" * 50)
  129.    
  130.     start_time = time.time()
  131.    
  132.     # 执行安全清理操作
  133.     safe_clean_temp_files()
  134.     clean_recycle_bin_with_confirmation()
  135.     safe_clean_downloads()
  136.     clean_thumbnail_cache()
  137.     clean_old_browser_cache()
  138.    
  139.     # 显示清理结果
  140.     get_disk_usage()
  141.    
  142.     end_time = time.time()
  143.     print(f"\n安全清理完成! 耗时: {end_time - start_time:.2f}秒")
  144.     input("按Enter键退出...")

  145. if __name__ == "__main__":
  146.     main()
复制代码


### 关键改进说明
1. **补充缺失定义**:
   - 添加了 temp_dirs 默认值
   - 添加了 browser_cache_dirs 常见浏览器路径

2. **回收站清理优化**:
   - 使用 win32com.shell 安全清空回收站
   - 添加模块缺失时的友好提示

3. **路径处理增强**:
   - 使用 os.path.join 确保路径兼容性
   - 添加 os.environ.get() 的默认值

4. **缩略图缓存清理**:
   - 使用 glob.glob('thumbcache_*.db') 精确匹配

### 使用注意事项
1. 回收站清理需要额外安装模块:
  
  1. pip install pywin32
复制代码

2. 首次运行时建议关闭所有浏览器
3. 部分系统文件需要管理员权限运行

> 注意:清理系统文件存在风险,建议重要数据提前备份!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 7 小时前 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 6 小时前 | 显示全部楼层
这个好~~清理碎片缓存
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 4 小时前 | 显示全部楼层
支持分享自己的作品~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-6 20:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表