|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码如下:- import os
- import shutil
- import tempfile
- import time
- import sys
- import glob
- def safe_clean_temp_files():
- """安全清理临时文件"""
- print("正在安全清理临时文件...")
- temp_dirs = [
- os.path.join(os.environ.get('USERPROFILE', r'C:\Users'), r'AppData\Local\Temp'),
- tempfile.gettempdir()
- ]
-
- for temp_dir in temp_dirs:
- try:
- if os.path.exists(temp_dir):
- for root, dirs, files in os.walk(temp_dir):
- for name in files:
- try:
- file_path = os.path.join(root, name)
- # 只删除7天前的临时文件
- if os.path.getmtime(file_path) < time.time() - 7 * 24 * 3600:
- os.remove(file_path)
- except (PermissionError, OSError):
- continue
- print(f"已安全清理: {temp_dir}")
- except Exception as e:
- print(f"清理 {temp_dir} 时出错: {e}")
- def clean_recycle_bin_with_confirmation():
- """带确认的清空回收站"""
- print("\n警告: 此操作将永久删除回收站中的所有文件!")
- confirm = input("确定要清空回收站吗? (y/n): ").lower()
- if confirm == 'y':
- try:
- # 使用内置方法模拟清空回收站
- recycle_bin = os.path.join(os.environ.get('SystemDrive', 'C:'), '$Recycle.Bin')
- if os.path.exists(recycle_bin):
- for item in os.listdir(recycle_bin):
- item_path = os.path.join(recycle_bin, item)
- try:
- if os.path.isdir(item_path):
- shutil.rmtree(item_path)
- else:
- os.remove(item_path)
- except (PermissionError, OSError):
- continue
- print("回收站已清空")
- except Exception as e:
- print(f"清空回收站时出错: {e}")
- else:
- print("跳过回收站清理")
- def clean_old_files(directory, days=30):
- """清理指定目录中超过指定天数的文件"""
- if not os.path.exists(directory):
- return
-
- cutoff = time.time() - days * 24 * 3600
- for filename in os.listdir(directory):
- filepath = os.path.join(directory, filename)
- try:
- if os.path.getmtime(filepath) < cutoff:
- if os.path.isfile(filepath):
- os.remove(filepath)
- elif os.path.isdir(filepath):
- shutil.rmtree(filepath)
- except (PermissionError, OSError):
- continue
- def safe_clean_downloads():
- """安全清理下载文件夹"""
- print("正在安全清理下载文件夹...")
- downloads_path = os.path.join(os.environ.get('USERPROFILE', r'C:\Users'), 'Downloads')
- clean_old_files(downloads_path, days=30)
- print("下载文件夹已安全清理")
- def clean_thumbnail_cache():
- """清理缩略图缓存"""
- print("正在清理缩略图缓存...")
- thumb_cache = os.path.join(os.environ.get('USERPROFILE', r'C:\Users'),
- r'AppData\Local\Microsoft\Windows\Explorer')
- if os.path.exists(thumb_cache):
- for filename in os.listdir(thumb_cache):
- if filename.startswith('thumbcache_'):
- try:
- os.remove(os.path.join(thumb_cache, filename))
- except (PermissionError, OSError):
- continue
- print("缩略图缓存已清理")
- def get_disk_usage():
- """显示磁盘使用情况"""
- total, used, free = shutil.disk_usage("C:")
- print("\n磁盘空间信息:")
- print(f"总空间: {total // (2**30)} GB")
- print(f"已使用: {used // (2**30)} GB")
- print(f"剩余空间: {free // (2**30)} GB")
- def clean_old_browser_cache(days=30):
- """清理超过指定天数的浏览器缓存"""
- appdata_local = os.getenv('LOCALAPPDATA')
- if not appdata_local:
- return
-
- cutoff_time = time.time() - days * 24 * 3600
-
- # Chrome/Edge/Brave缓存文件通常以以下扩展名结尾
- cache_file_patterns = [
- '_*', 'f_*', 'data_*', 'index'
- ]
-
- browser_cache_dirs = [
- os.path.join(appdata_local, 'Google', 'Chrome', 'User Data'),
- os.path.join(appdata_local, 'Microsoft', 'Edge', 'User Data'),
- os.path.join(appdata_local, 'BraveSoftware', 'Brave-Browser', 'User Data')
- ]
-
- for cache_dir in browser_cache_dirs:
- if not os.path.exists(cache_dir):
- continue
-
- # 查找所有Profile的Cache目录
- for profile_dir in glob.glob(os.path.join(cache_dir, '*')):
- cache_path = os.path.join(profile_dir, 'Cache')
- if os.path.exists(cache_path):
- print(f"正在检查: {cache_path}")
- for root, _, files in os.walk(cache_path):
- for file in files:
- file_path = os.path.join(root, file)
- try:
- if os.path.getmtime(file_path) < cutoff_time:
- os.remove(file_path)
- except:
- continue
- def main():
- print("C盘安全清理工具 (仅使用内置库)")
- print("=" * 50)
-
-
- start_time = time.time()
-
- # 执行安全清理操作
- safe_clean_temp_files()
- clean_recycle_bin_with_confirmation()
- safe_clean_downloads()
- clean_thumbnail_cache()
- clean_old_browser_cache()
-
- # 显示清理结果
- get_disk_usage()
-
- end_time = time.time()
- print(f"\n安全清理完成! 耗时: {end_time - start_time:.2f}秒")
- input("按Enter键退出...")
- if __name__ == "__main__":
- main()
复制代码 |
-
-
评分
-
参与人数 2 | 荣誉 +3 |
鱼币 +7 |
贡献 +3 |
C币 +3 |
收起
理由
|
小甲鱼
| + 3 |
+ 3 |
+ 3 |
+ 3 |
无条件支持楼主! |
某一个“天”
| |
+ 4 |
|
|
能给我的作品评个分吗 |
查看全部评分
|