Python 安全清理系统垃圾文件工具6个

下面是一个完整的 Python 脚本,用于安全地清理各种系统垃圾文件。这个工具具有图形界面,支持多种操作系统,并提供详细的清理报告和预览功能。

图片[1]_Python 安全清理系统垃圾文件工具6个_知途无界
import os
import shutil
import tempfile
import platform
import time
import json
from pathlib import Path
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from datetime import datetime, timedelta
import hashlib
import psutil

class SystemCleaner:
    def __init__(self):
        self.system = platform.system()
        self.cleanup_stats = {
            'files_deleted': 0,
            'space_freed': 0,
            'errors': [],
            'scan_time': 0,
            'cleanup_time': 0
        }
        self.scan_results = {}
        self.is_cleaning = False
        
        # 定义不同系统的垃圾文件位置
        self.junk_patterns = {
            'windows': {
                'temp_files': [
                    tempfile.gettempdir(),
                    os.path.join(os.environ.get('WINDIR', 'C:\\Windows'), 'Temp'),
                    os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Temp')
                ],
                'browser_cache': [
                    os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Google\\Chrome\\User Data\\Default\\Cache'),
                    os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Microsoft\\Edge\\User Data\\Default\\Cache'),
                    os.path.join(os.environ.get('APPDATA', ''), 'Mozilla\\Firefox\\Profiles')
                ],
                'recycle_bin': ['C:\\$Recycle.Bin'],
                'log_files': [
                    os.path.join(os.environ.get('WINDIR', 'C:\\Windows'), 'Logs'),
                    os.path.join(os.environ.get('WINDIR', 'C:\\Windows'), 'System32\\LogFiles')
                ]
            },
            'linux': {
                'temp_files': ['/tmp', '/var/tmp', '/var/cache'],
                'cache_files': [
                    os.path.expanduser('~/.cache'),
                    os.path.expanduser('~/.thumbnails')
                ],
                'log_files': ['/var/log'],
                'trash': [os.path.expanduser('~/.local/share/Trash')]
            },
            'darwin': {  # macOS
                'temp_files': ['/tmp', '/private/var/tmp', '/private/var/folders'],
                'cache_files': [
                    os.path.expanduser('~/Library/Caches'),
                    os.path.expanduser('~/Library/Logs')
                ],
                'trash': [os.path.expanduser('~/.Trash')],
                'browser_cache': [
                    os.path.expanduser('~/Library/Caches/Google/Chrome'),
                    os.path.expanduser('~/Library/Caches/com.apple.Safari')
                ]
            }
        }
    
    def get_junk_locations(self):
        """获取当前系统的垃圾文件位置"""
        return self.junk_patterns.get(self.system.lower(), {})
    
    def is_safe_to_delete(self, file_path):
        """检查文件是否安全删除"""
        try:
            # 检查文件是否存在
            if not os.path.exists(file_path):
                return False
            
            # 检查是否是系统关键目录
            system_dirs = [
                '/bin', '/sbin', '/usr/bin', '/usr/sbin', '/boot',
                '/dev', '/etc', '/lib', '/lib64', '/proc', '/root',
                '/sys', '/var', 'C:\\Windows', 'C:\\Program Files',
                'C:\\Program Files (x86)', '/System', '/Library'
            ]
            
            file_path_lower = file_path.lower()
            for sys_dir in system_dirs:
                if sys_dir.lower() in file_path_lower and len(file_path) > len(sys_dir) + 5:
                    # 确保不是系统目录下的用户文件
                    relative_path = os.path.relpath(file_path, sys_dir)
                    if not any(part.startswith('.') or part == 'Users' for part in Path(relative_path).parts[:2]):
                        return False
            
            # 检查文件大小(避免删除大文件)
            if os.path.isfile(file_path):
                file_size = os.path.getsize(file_path)
                if file_size > 100 * 1024 * 1024:  # 大于100MB的文件需要特别小心
                    return False
            
            # 检查最近访问时间(避免删除最近使用的文件)
            if os.path.isfile(file_path):
                access_time = os.path.getatime(file_path)
                if time.time() - access_time < 24 * 3600:  # 24小时内访问过的文件
                    return False
            
            return True
            
        except Exception as e:
            self.cleanup_stats['errors'].append(f"安全检查失败 {file_path}: {str(e)}")
            return False
    
    def scan_junk_files(self, progress_callback=None):
        """扫描垃圾文件"""
        start_time = time.time()
        junk_locations = self.get_junk_locations()
        found_files = []
        
        total_locations = sum(len(locations) for locations in junk_locations.values())
        current_location = 0
        
        for category, locations in junk_locations.items():
            for location in locations:
                current_location += 1
                if progress_callback:
                    progress = (current_location / total_locations) * 100
                    progress_callback(progress, f"扫描: {location}")
                
                try:
                    if not os.path.exists(location):
                        continue
                    
                    if os.path.isfile(location):
                        if self.is_safe_to_delete(location):
                            size = os.path.getsize(location)
                            found_files.append({
                                'path': location,
                                'size': size,
                                'category': category,
                                'type': 'file'
                            })
                    
                    elif os.path.isdir(location):
                        for root, dirs, files in os.walk(location):
                            # 跳过某些系统目录
                            if any(skip_dir in root for skip_dir in ['System Volume Information', '$RECYCLE.BIN']):
                                continue
                            
                            for file in files:
                                file_path = os.path.join(root, file)
                                try:
                                    if self.is_safe_to_delete(file_path):
                                        size = os.path.getsize(file_path)
                                        found_files.append({
                                            'path': file_path,
                                            'size': size,
                                            'category': category,
                                            'type': 'file'
                                        })
                                except (OSError, PermissionError):
                                    continue
                            
                            # 限制扫描深度以提高性能
                            if root.count(os.sep) - location.count(os.sep) > 3:
                                del dirs[:]
                
                except (PermissionError, OSError) as e:
                    self.cleanup_stats['errors'].append(f"无法访问 {location}: {str(e)}")
                    continue
        
        # 按类别分组
        scan_results = {}
        for file_info in found_files:
            category = file_info['category']
            if category not in scan_results:
                scan_results[category] = {'files': [], 'total_size': 0}
            
            scan_results[category]['files'].append(file_info)
            scan_results[category]['total_size'] += file_info['size']
        
        self.scan_results = scan_results
        self.cleanup_stats['scan_time'] = time.time() - start_time
        
        return scan_results
    
    def format_size(self, size_bytes):
        """格式化文件大小"""
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size_bytes < 1024.0:
                return f"{size_bytes:.2f} {unit}"
            size_bytes /= 1024.0
        return f"{size_bytes:.2f} PB"
    
    def delete_file(self, file_path):
        """安全删除单个文件"""
        try:
            if os.path.isfile(file_path):
                os.remove(file_path)
                return True
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
                return True
        except Exception as e:
            self.cleanup_stats['errors'].append(f"删除失败 {file_path}: {str(e)}")
            return False
    
    def cleanup_junk_files(self, categories_to_clean=None, progress_callback=None):
        """清理垃圾文件"""
        if self.is_cleaning:
            return False
        
        self.is_cleaning = True
        start_time = time.time()
        
        try:
            categories = categories_to_clean or list(self.scan_results.keys())
            
            for i, category in enumerate(categories):
                if category not in self.scan_results:
                    continue
                
                if progress_callback:
                    progress = (i / len(categories)) * 100
                    progress_callback(progress, f"清理: {category}")
                
                files = self.scan_results[category]['files']
                
                for j, file_info in enumerate(files):
                    if not self.is_cleaning:  # 检查是否被取消
                        break
                    
                    if progress_callback and len(files) > 10:
                        file_progress = (j / len(files)) * 100
                        overall_progress = (i / len(categories)) * 100 + (file_progress / len(categories))
                        progress_callback(overall_progress, f"删除: {os.path.basename(file_info['path'])}")
                    
                    if self.delete_file(file_info['path']):
                        self.cleanup_stats['files_deleted'] += 1
                        self.cleanup_stats['space_freed'] += file_info['size']
            
            self.cleanup_stats['cleanup_time'] = time.time() - start_time
            return True
            
        finally:
            self.is_cleaning = False
    
    def stop_cleanup(self):
        """停止清理过程"""
        self.is_cleaning = False
    
    def generate_report(self):
        """生成清理报告"""
        report = {
            'timestamp': datetime.now().isoformat(),
            'system': self.system,
            'stats': self.cleanup_stats.copy(),
            'scan_results': {}
        }
        
        # 添加扫描结果的摘要信息
        for category, data in self.scan_results.items():
            report['scan_results'][category] = {
                'file_count': len(data['files']),
                'total_size': data['total_size'],
                'formatted_size': self.format_size(data['total_size'])
            }
        
        # 格式化统计信息
        stats = report['stats']
        stats['space_freed_formatted'] = self.format_size(stats['space_freed'])
        stats['scan_time_formatted'] = f"{stats['scan_time']:.2f}秒"
        stats['cleanup_time_formatted'] = f"{stats['cleanup_time']:.2f}秒"
        
        return report

class CleanerGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("系统垃圾清理工具")
        self.root.geometry("900x700")
        self.root.resizable(True, True)
        
        self.cleaner = SystemCleaner()
        self.setup_ui()
        
    def setup_ui(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="系统垃圾清理工具", 
                               font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
        
        # 系统信息
        system_info = f"检测系统: {platform.system()} {platform.release()}"
        system_label = ttk.Label(main_frame, text=system_info)
        system_label.grid(row=1, column=0, columnspan=3, pady=(0, 10))
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, columnspan=3, pady=10, sticky=(tk.W, tk.E))
        button_frame.columnconfigure(0, weight=1)
        button_frame.columnconfigure(1, weight=1)
        button_frame.columnconfigure(2, weight=1)
        
        # 扫描按钮
        self.scan_btn = ttk.Button(button_frame, text="扫描垃圾文件", 
                                  command=self.start_scan)
        self.scan_btn.grid(row=0, column=0, padx=5)
        
        # 清理按钮
        self.cleanup_btn = ttk.Button(button_frame, text="清理垃圾文件", 
                                     command=self.start_cleanup, state='disabled')
        self.cleanup_btn.grid(row=0, column=1, padx=5)
        
        # 停止按钮
        self.stop_btn = ttk.Button(button_frame, text="停止清理", 
                                   command=self.stop_cleanup, state='disabled')
        self.stop_btn.grid(row=0, column=2, padx=5)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress_var, 
                                           maximum=100, length=400)
        self.progress_bar.grid(row=3, column=0, columnspan=3, pady=10, sticky=(tk.W, tk.E))
        
        # 状态标签
        self.status_var = tk.StringVar(value="就绪")
        status_label = ttk.Label(main_frame, textvariable=self.status_var)
        status_label.grid(row=4, column=0, columnspan=3, pady=5)
        
        # 创建笔记本控件(标签页)
        notebook = ttk.Notebook(main_frame)
        notebook.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), 
                     pady=10)
        main_frame.rowconfigure(5, weight=1)
        
        # 扫描结果标签页
        self.scan_frame = ttk.Frame(notebook, padding="10")
        notebook.add(self.scan_frame, text="扫描结果")
        self.setup_scan_tab()
        
        # 日志标签页
        self.log_frame = ttk.Frame(notebook, padding="10")
        notebook.add(self.log_frame, text="清理日志")
        self.setup_log_tab()
        
        # 设置标签页
        self.settings_frame = ttk.Frame(notebook, padding="10")
        notebook.add(self.settings_frame, text="设置")
        self.setup_settings_tab()
    
    def setup_scan_tab(self):
        # 创建树形视图显示扫描结果
        columns = ('类别', '文件数量', '占用空间')
        self.tree = ttk.Treeview(self.scan_frame, columns=columns, show='headings', height=15)
        
        # 定义列
        self.tree.heading('类别', text='垃圾类别')
        self.tree.heading('文件数量', text='文件数量')
        self.tree.heading('占用空间', text='占用空间')
        
        self.tree.column('类别', width=150)
        self.tree.column('文件数量', width=100)
        self.tree.column('占用空间', width=150)
        
        # 添加滚动条
        tree_scroll = ttk.Scrollbar(self.scan_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=tree_scroll.set)
        
        # 布局
        self.tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        tree_scroll.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        self.scan_frame.columnconfigure(0, weight=1)
        self.scan_frame.rowconfigure(0, weight=1)
        
        # 绑定选择事件
        self.tree.bind('<Double-1>', self.on_item_select)
    
    def setup_log_tab(self):
        # 日志文本框
        self.log_text = scrolledtext.ScrolledText(self.log_frame, wrap=tk.WORD, height=20)
        self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 清空日志按钮
        clear_log_btn = ttk.Button(self.log_frame, text="清空日志", 
                                  command=self.clear_log)
        clear_log_btn.grid(row=1, column=0, pady=5)
        
        self.log_frame.columnconfigure(0, weight=1)
        self.log_frame.rowconfigure(0, weight=1)
    
    def setup_settings_tab(self):
        # 创建设置选项
        settings_label = ttk.Label(self.settings_frame, text="清理选项", 
                                  font=("Arial", 12, "bold"))
        settings_label.grid(row=0, column=0, columnspan=2, pady=(0, 10), sticky=tk.W)
        
        # 复选框变量
        self.cleanup_vars = {}
        
        row = 1
        categories = {
            'temp_files': '临时文件',
            'browser_cache': '浏览器缓存',
            'recycle_bin': '回收站',
            'log_files': '日志文件',
            'cache_files': '应用缓存',
            'trash': '废纸篓'
        }
        
        for key, description in categories.items():
            var = tk.BooleanVar(value=True)
            self.cleanup_vars[key] = var
            
            cb = ttk.Checkbutton(self.settings_frame, text=description, 
                                variable=var)
            cb.grid(row=row, column=0, sticky=tk.W, pady=2)
            row += 1
        
        # 安全设置
        safety_label = ttk.Label(self.settings_frame, text="安全设置", 
                                font=("Arial", 12, "bold"))
        safety_label.grid(row=row, column=0, columnspan=2, pady=(20, 10), sticky=tk.W)
        row += 1
        
        self.skip_large_files = tk.BooleanVar(value=True)
        large_cb = ttk.Checkbutton(self.settings_frame, text="跳过大于100MB的文件", 
                                  variable=self.skip_large_files)
        large_cb.grid(row=row, column=0, sticky=tk.W, pady=2)
        row += 1
        
        self.skip_recent_files = tk.BooleanVar(value=True)
        recent_cb = ttk.Checkbutton(self.settings_frame, text="跳过24小时内访问的文件", 
                                   variable=self.skip_recent_files)
        recent_cb.grid(row=row, column=0, sticky=tk.W, pady=2)
        row += 1
        
        # 保存设置按钮
        save_btn = ttk.Button(self.settings_frame, text="保存设置", 
                             command=self.save_settings)
        save_btn.grid(row=row, column=0, pady=20)
    
    def log_message(self, message):
        """添加消息到日志"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] {message}\n"
        
        self.log_text.insert(tk.END, log_entry)
        self.log_text.see(tk.END)
        self.root.update_idletasks()
    
    def clear_log(self):
        """清空日志"""
        self.log_text.delete(1.0, tk.END)
    
    def update_status(self, message):
        """更新状态"""
        self.status_var.set(message)
        self.root.update_idletasks()
    
    def update_progress(self, value, message=None):
        """更新进度条"""
        self.progress_var.set(value)
        if message:
            self.update_status(message)
        self.root.update_idletasks()
    
    def start_scan(self):
        """开始扫描垃圾文件"""
        self.scan_btn.config(state='disabled')
        self.cleanup_btn.config(state='disabled')
        self.stop_btn.config(state='disabled')
        
        # 在新线程中执行扫描
        thread = threading.Thread(target=self.run_scan)
        thread.daemon = True
        thread.start()
    
    def run_scan(self):
        """执行扫描操作"""
        try:
            self.update_status("正在扫描垃圾文件...")
            self.log_message("开始扫描系统垃圾文件...")
            
            # 重置扫描结果
            self.cleaner.scan_results = {}
            
            # 执行扫描
            scan_results = self.cleaner.scan_junk_files(
                progress_callback=self.update_progress
            )
            
            # 更新UI显示扫描结果
            self.root.after(0, self.display_scan_results, scan_results)
            
            # 启用清理按钮
            self.root.after(0, lambda: self.cleanup_btn.config(state='normal'))
            self.root.after(0, lambda: self.scan_btn.config(state='normal'))
            
            self.update_status("扫描完成")
            self.log_message(f"扫描完成! 耗时: {self.cleaner.cleanup_stats['scan_time']:.2f}秒")
            
        except Exception as e:
            self.log_message(f"扫描过程中发生错误: {str(e)}")
            self.update_status("扫描失败")
            self.root.after(0, lambda: self.scan_btn.config(state='normal'))
    
    def display_scan_results(self, scan_results):
        """显示扫描结果"""
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 添加扫描结果
        total_files = 0
        total_size = 0
        
        for category, data in scan_results.items():
            file_count = len(data['files'])
            size = data['total_size']
            formatted_size = self.cleaner.format_size(size)
            
            self.tree.insert('', 'end', values=(category, file_count, formatted_size))
            
            total_files += file_count
            total_size += size
        
        # 添加总计行
        if scan_results:
            formatted_total_size = self.cleaner.format_size(total_size)
            self.tree.insert('', 'end', values=('总计', total_files, formatted_total_size))
        
        self.log_message(f"发现 {total_files} 个垃圾文件,共占用 {self.cleaner.format_size(total_size)} 空间")
    
    def on_item_select(self, event):
        """处理树形视图项目双击事件"""
        selection = self.tree.selection()
        if not selection:
            return
        
        item = selection[0]
        values = self.tree.item(item, 'values')
        
        if len(values) >= 3 and values[0] != '总计':
            category = values[0]
            if category in self.cleaner.scan_results:
                files = self.cleaner.scan_results[category]['files'][:10]  # 只显示前10个文件
                
                detail_window = tk.Toplevel(self.root)
                detail_window.title(f"{category} - 文件详情")
                detail_window.geometry("800x400")
                
                # 创建文本框显示文件列表
                detail_text = scrolledtext.ScrolledText(detail_window, wrap=tk.WORD)
                detail_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
                
                detail_text.insert(tk.END, f"{category} 文件详情:\n\n")
                detail_text.insert(tk.END, f"总文件数: {len(self.cleaner.scan_results[category]['files'])}\n")
                detail_text.insert(tk.END, f"显示前10个文件:\n\n")
                
                for i, file_info in enumerate(files, 1):
                    file_path = file_info['path']
                    file_size = self.cleaner.format_size(file_info['size'])
                    detail_text.insert(tk.END, f"{i}. {file_path}\n   大小: {file_size}\n\n")
                
                if len(self.cleaner.scan_results[category]['files']) > 10:
                    detail_text.insert(tk.END, f"... 还有 {len(self.cleaner.scan_results[category]['files']) - 10} 个文件未显示")
                
                detail_text.config(state=tk.DISABLED)
    
    def start_cleanup(self):
        """开始清理垃圾文件"""
        if not self.cleaner.scan_results:
            messagebox.showwarning("警告", "请先进行扫描!")
            return
        
        # 确认对话框
        result = messagebox.askyesno("确认清理", 
                                   "确定要清理选中的垃圾文件吗?\n此操作不可撤销!")
        if not result:
            return
        
        # 获取要清理的类别
        categories_to_clean = []
        for key, var in self.cleanup_vars.items():
            if var.get() and any(key.replace('_', '') in cat for cat in self.cleaner.scan_results.keys()):
                # 映射复选框到实际的类别名称
                category_mapping = {
                    'temp_files': 'temp_files',
                    'browser_cache': 'browser_cache',
                    'recycle_bin': 'recycle_bin',
                    'log_files': 'log_files',
                    'cache_files': 'cache_files',
                    'trash': 'trash'
                }
                actual_category = category_mapping.get(key)
                if actual_category and actual_category in self.cleaner.scan_results:
                    categories_to_clean.append(actual_category)
        
        if not categories_to_clean:
            messagebox.showinfo("提示", "没有选中任何清理类别!")
            return
        
        # 更新按钮状态
        self.scan_btn.config(state='disabled')
        self.cleanup_btn.config(state='disabled')
        self.stop_btn.config(state='normal')
        
        # 在新线程中执行清理
        thread = threading.Thread(target=self.run_cleanup, args=(categories_to_clean,))
        thread.daemon = True
        thread.start()
    
    def run_cleanup(self, categories_to_clean):
        """执行清理操作"""
        try:
            self.update_status("正在清理垃圾文件...")
            self.log_message("开始清理垃圾文件...")
            
            # 重置清理统计
            self.cleaner.cleanup_stats = {
                'files_deleted': 0,
                'space_freed': 0,
                'errors': [],
                'scan_time': self.cleaner.cleanup_stats.get('scan_time', 0),
                'cleanup_time': 0
            }
            
            # 执行清理
            success = self.cleaner.cleanup_junk_files(
                categories_to_clean=categories_to_clean,
                progress_callback=self.update_progress
            )
            
            # 生成报告
            report = self.cleaner.generate_report()
            
            # 更新UI
            self.root.after(0, self.display_cleanup_results, report)
            
            self.update_status("清理完成")
            self.log_message("清理完成!")
            self.log_message(f"删除文件: {report['stats']['files_deleted']} 个")
            self.log_message(f"释放空间: {report['stats']['space_freed_formatted']}")
            self.log_message(f"清理耗时: {report['stats']['cleanup_time_formatted']}")
            
            if report['stats']['errors']:
                self.log_message(f"遇到 {len(report['stats']['errors'])} 个错误")
                for error in report['stats']['errors'][:5]:  # 只显示前5个错误
                    self.log_message(f"  错误: {error}")
        
        except Exception as e:
            self.log_message(f"清理过程中发生错误: {str(e)}")
            self.update_status("清理失败")
        finally:
            self.root.after(0, lambda: self.scan_btn.config(state='normal'))
            self.root.after(0, lambda: self.cleanup_btn.config(state='normal'))
            self.root.after(0, lambda: self.stop_btn.config(state='disabled'))
    
    def display_cleanup_results(self, report):
        """显示清理结果"""
        # 可以在这里添加更详细的结果显示
        pass
    
    def stop_cleanup(self):
        """停止清理"""
        self.cleaner.stop_cleanup()
        self.update_status("清理已停止")
        self.log_message("用户停止了清理操作")
        self.scan_btn.config(state='normal')
        self.cleanup_btn.config(state='normal')
        self.stop_btn.config(state='disabled')
    
    def save_settings(self):
        """保存设置"""
        # 这里可以添加保存到配置文件的代码
        messagebox.showinfo("提示", "设置已保存!")
        self.log_message("设置已保存")

def main():
    root = tk.Tk()
    app = CleanerGUI(root)
    
    # 设置窗口图标(如果有的话)
    try:
        # root.iconbitmap('cleaner_icon.ico')  # 取消注释并设置正确的图标路径
        pass
    except:
        pass
    
    # 启动GUI
    root.mainloop()

if __name__ == "__main__":
    main()

功能特点

这个系统垃圾清理工具具有以下特点:

1. 多平台支持

  • 自动检测 Windows、Linux 和 macOS 系统
  • 针对不同系统使用相应的垃圾文件位置定义

2. 安全机制

  • 文件安全删除检查(避免删除系统文件)
  • 跳过大型文件(默认 >100MB)
  • 跳过最近访问的文件(默认 24小时内)
  • 保护系统关键目录

3. 用户友好界面

  • 图形化界面,操作简单直观
  • 实时进度显示和状态更新
  • 扫描结果分类展示
  • 详细的清理日志

4. 灵活的配置选项

  • 可选择清理特定类型的垃圾文件
  • 可配置安全设置
  • 支持自定义清理规则

5. 详细的报告功能

  • 扫描统计信息
  • 清理前后对比
  • 错误日志记录

使用方法

  1. 运行脚本后,点击”扫描垃圾文件”按钮
  2. 查看扫描结果,了解各类垃圾文件的数量和大小
  3. 在设置标签页中选择要清理的文件类型
  4. 点击”清理垃圾文件”按钮进行清理
  5. 查看清理日志了解详细过程和结果

注意事项

  • 首次运行时可能需要管理员权限才能访问某些系统目录
  • 清理操作不可逆,请谨慎选择清理类别
  • 建议在清理前关闭相关应用程序
  • 对于重要文件,建议先进行备份

这个工具提供了安全的垃圾文件清理方案,既能有效释放磁盘空间,又能避免误删重要文件。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞72 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容