【使用 Python 脚本彻底清理 Windows 电脑垃圾】

在日常使用 Windows 电脑的过程中,系统会生成大量的临时文件、缓存、日志文件等,这些文件会占用磁盘空间,影响系统性能。虽然 Windows 自带磁盘清理工具,但我们可以利用 Python 脚本更全面地清理系统中的各种垃圾文件。这篇教程将教你如何编写一个 Python 脚本来自动化这个清理过程。

脚本功能概述

这个 Python 脚本的主要功能是删除 Windows 系统中的临时文件、浏览器缓存、应用缓存、系统日志文件、预读取文件等,并执行一些额外的清理任务,比如清空回收站、清理 DNS 缓存和注册表垃圾等。脚本的设计思路是尽可能覆盖常见的系统垃圾文件位置,做到彻底清理。

代码实现

首先,我们需要导入一些 Python 内置模块来完成文件操作、注册表操作和系统命令执行。

import os
import shutil
import subprocess
import winreg

 
 

接下来,定义一个通用的函数,用于删除指定文件夹中的所有文件和子文件夹:

def delete_files_in_folder(folder_path):
    if os.path.exists(folder_path):
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f'Failed to delete {file_path}. Reason: {e}')

 
 

这个函数会遍历给定路径下的所有文件和文件夹,并尝试删除它们。如果发生错误,会捕获异常并输出错误信息。

清理临时文件

Windows 会在多个位置存储临时文件,我们可以通过以下函数来清理这些位置:

def clean_temp_files():
    temp_folders = [
        os.getenv('TEMP'),
        os.getenv('TMP'),
        os.path.join(os.getenv('SystemRoot'), 'Temp'),
    ]
    for temp_folder in temp_folders:
        delete_files_in_folder(temp_folder)

 
 
清理浏览器缓存

浏览器缓存会占用大量空间,可以使用以下代码清理常用浏览器(如 Chrome、Firefox 和 Edge)的缓存:

def clean_browser_cache():
    browser_cache_paths = [
        os.path.expanduser('~\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache'),
        os.path.expanduser('~\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\'),
        os.path.expanduser('~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cache'),
    ]
    for cache_path in browser_cache_paths:
        if os.path.exists(cache_path):
            shutil.rmtree(cache_path, ignore_errors=True)

 
 
清理应用缓存和其他系统文件

此外,我们还可以清理应用缓存、Windows 更新缓存、系统错误报告文件、预读取文件、日志文件、下载文件夹等:

def clean_app_cache():
    app_cache_paths = [
        os.path.expanduser('~\\AppData\\Local\\Temp'),
        os.path.expanduser('~\\AppData\\Roaming\\Temp'),
        os.path.expanduser('~\\AppData\\LocalLow\\Temp'),
    ]
    for cache_path in app_cache_paths:
        delete_files_in_folder(cache_path)
def clean_windows_update_cache():
    update_cache_path = os.path.join(os.getenv('SystemRoot'), 'SoftwareDistribution', 'Download')
    delete_files_in_folder(update_cache_path)
def clean_system_error_reports():
    error_report_paths = [
        os.path.join(os.getenv('SystemRoot'), 'System32', 'LogFiles', 'WMI'),
        os.path.join(os.getenv('SystemRoot'), 'System32', 'winevt', 'Logs'),
        os.path.expanduser('~\\AppData\\Local\\CrashDumps'),
    ]
    for error_report_path in error_report_paths:
        delete_files_in_folder(error_report_path)
def clean_prefetch():
    prefetch_path = os.path.join(os.getenv('SystemRoot'), 'Prefetch')
    delete_files_in_folder(prefetch_path)
def empty_recycle_bin():
    subprocess.run(['PowerShell', '-Command', 'Clear-RecycleBin', '-Force'])
def clean_log_files():
    log_file_paths = [
        os.path.join(os.getenv('SystemRoot'), 'Logs'),
        os.path.join(os.getenv('SystemRoot'), 'System32', 'LogFiles'),
    ]
    for log_file_path in log_file_paths:
        delete_files_in_folder(log_file_path)
def clean_downloads():
    downloads_folder = os.path.expanduser('~\\Downloads')
    delete_files_in_folder(downloads_folder)

 
 
执行系统命令进行额外清理

我们还可以调用一些系统命令来执行特定的清理任务,比如磁盘清理工具、清理 DNS 缓存和删除旧版 Windows 更新文件:

def run_disk_cleanup():
    subprocess.run(['cleanmgr', '/sagerun:1'])
def clean_windows_old():
    windows_old = os.path.join(os.getenv('SystemDrive'), 'Windows.old')
    if os.path.exists(windows_old):
        shutil.rmtree(windows_old, ignore_errors=True)
def clean_dns_cache():
    subprocess.run(['ipconfig', '/flushdns'])

 
 
清理注册表垃圾

最后,我们可以通过访问注册表来清理一些未使用的注册表项:

def clean_registry():
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_SET_VALUE) as key:
            winreg.DeleteValue(key, 'SomeUnusedKey')  # 示例:删除未使用的注册表项
    except Exception as e:
        print(f"Failed to clean registry. Reason: {e}")

 
 
完整脚本的执行

我们将所有的清理任务整合到一个主函数 main() 中,并在脚本入口处调用它:

import os
import shutil
import subprocess
import winreg
# 删除指定文件夹中的所有文件和文件夹
def delete_files_in_folder(folder_path):
    if os.path.exists(folder_path):
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f'Failed to delete {file_path}. Reason: {e}')
# 清理Windows临时文件
def clean_temp_files():
    temp_folders = [
        os.getenv('TEMP'),
        os.getenv('TMP'),
        os.path.join(os.getenv('SystemRoot'), 'Temp'),
    ]
    for temp_folder in temp_folders:
        delete_files_in_folder(temp_folder)
# 清理浏览器缓存
def clean_browser_cache():
    browser_cache_paths = [
        os.path.expanduser('~\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache'),
        os.path.expanduser('~\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\'),
        os.path.expanduser('~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cache'),
    ]
    for cache_path in browser_cache_paths:
        if os.path.exists(cache_path):
            shutil.rmtree(cache_path, ignore_errors=True)
# 清理应用缓存
def clean_app_cache():
    app_cache_paths = [
        os.path.expanduser('~\\AppData\\Local\\Temp'),
        os.path.expanduser('~\\AppData\\Roaming\\Temp'),
        os.path.expanduser('~\\AppData\\LocalLow\\Temp'),
    ]
    for cache_path in app_cache_paths:
        delete_files_in_folder(cache_path)
# 清理Windows更新缓存
def clean_windows_update_cache():
    update_cache_path = os.path.join(os.getenv('SystemRoot'), 'SoftwareDistribution', 'Download')
    delete_files_in_folder(update_cache_path)
# 清理系统错误报告文件
def clean_system_error_reports():
    error_report_paths = [
        os.path.join(os.getenv('SystemRoot'), 'System32', 'LogFiles', 'WMI'),
        os.path.join(os.getenv('SystemRoot'), 'System32', 'winevt', 'Logs'),
        os.path.expanduser('~\\AppData\\Local\\CrashDumps'),
    ]
    for error_report_path in error_report_paths:
        delete_files_in_folder(error_report_path)
# 清理预读取文件
def clean_prefetch():
    prefetch_path = os.path.join(os.getenv('SystemRoot'), 'Prefetch')
    delete_files_in_folder(prefetch_path)
# 清理回收站
def empty_recycle_bin():
    subprocess.run(['PowerShell', '-Command', 'Clear-RecycleBin', '-Force'])
# 清理日志文件
def clean_log_files():
    log_file_paths = [
        os.path.join(os.getenv('SystemRoot'), 'Logs'),
        os.path.join(os.getenv('SystemRoot'), 'System32', 'LogFiles'),
    ]
    for log_file_path in log_file_paths:
        delete_files_in_folder(log_file_path)
# 删除下载文件夹中的内容
def clean_downloads():
    downloads_folder = os.path.expanduser('~\\Downloads')
    delete_files_in_folder(downloads_folder)
# 运行磁盘清理工具
def run_disk_cleanup():
    subprocess.run(['cleanmgr', '/sagerun:1'])
# 删除Windows旧版更新文件
def clean_windows_old():
    windows_old = os.path.join(os.getenv('SystemDrive'), 'Windows.old')
    if os.path.exists(windows_old):
        shutil.rmtree(windows_old, ignore_errors=True)
# 清理DNS缓存
def clean_dns_cache():
    subprocess.run(['ipconfig', '/flushdns'])
# 清理注册表垃圾(示例)
def clean_registry():
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_SET_VALUE) as key:
            winreg.DeleteValue(key, 'SomeUnusedKey')  # 示例:删除未使用的注册表项
    except Exception as e:
        print(f"Failed to clean registry. Reason: {e}")
def main():
    print("开始彻底清理电脑垃圾...")
    clean_temp_files()
    clean_browser_cache()
    clean_app_cache()
    clean_windows_update_cache()
    clean_system_error_reports()
    clean_prefetch()
    empty_recycle_bin()
    clean_log_files()
    clean_downloads()
    clean_windows_old()
    clean_dns_cache()
    clean_registry()
    run_disk_cleanup()
    print("彻底清理完成!")
if __name__ == "__main__":
    main()

 
 
总结

通过这个脚本,我们可以方便地清理 Windows 电脑上的各类垃圾文件,释放磁盘空间,保持系统流畅运行。这个脚本不仅可以作为个人使用,还可以根据需要进一步扩展和定制,以适应不同的清理需求。

你可以将这个脚本保存为 .py 文件,并在需要清理系统时运行它。希望这篇教程对你有帮助!如果你对脚本有任何疑问或改进建议,欢迎留言讨论!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值