|
在日常使用Windows电脑的过程中,系统会生成大量的临时文件、缓存、日志文件等,这些文件会占用磁盘空间,影响系统性能。虽然Windows自带磁盘清理工具,但我们可以利用Python脚本更全面地清理系统中的各种垃圾文件。这篇教程将教你如何编写一个Python脚本来自动化这个清理过程。脚本功能概述这个Python脚本的主要功能是删除Windows系统中的临时文件、浏览器缓存、应用缓存、系统日志文件、预读取文件等,并执行一些额外的清理任务,比如清空回收站、清理DNS缓存和注册表垃圾等。脚本的设计思路是尽可能覆盖常见的系统垃圾文件位置,做到彻底清理。代码实现首先,我们需要导入一些Python内置模块来完成文件操作、注册表操作和系统命令执行。importosimportshutilimportsubprocessimportwinreg1234接下来,定义一个通用的函数,用于删除指定文件夹中的所有文件和子文件夹:defdelete_files_in_folder(folder_path):ifos.path.exists(folder_path):forfilenameinos.listdir(folder_path):file_path=os.path.join(folder_path,filename)try:ifos.path.isfile(file_path)oros.path.islink(file_path)s.unlink(file_path)elifos.path.isdir(file_path):shutil.rmtree(file_path)exceptExceptionase:print(f'Failedtodelete{file_path}.Reason:{e}')1234567891011这个函数会遍历给定路径下的所有文件和文件夹,并尝试删除它们。如果发生错误,会捕获异常并输出错误信息。清理临时文件Windows会在多个位置存储临时文件,我们可以通过以下函数来清理这些位置:defclean_temp_files():temp_folders=[os.getenv('TEMP'),os.getenv('TMP'),os.path.join(os.getenv('SystemRoot'),'Temp'),]fortemp_folderintemp_folders:delete_files_in_folder(temp_folder)123456789清理浏览器缓存浏览器缓存会占用大量空间,可以使用以下代码清理常用浏览器(如Chrome、Firefox和Edge)的缓存:defclean_browser_cache():browser_cache_paths=[os.path.expanduser('~\\AppData\\Local\\Google\\Chrome\\UserData\\Default\\Cache'),os.path.expanduser('~\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\'),os.path.expanduser('~\\AppData\\Local\\Microsoft\\Edge\\UserData\\Default\\Cache'),]forcache_pathinbrowser_cache_paths:ifos.path.exists(cache_path):shutil.rmtree(cache_path,ignore_errors=True)12345678910清理应用缓存和其他系统文件此外,我们还可以清理应用缓存、Windows更新缓存、系统错误报告文件、预读取文件、日志文件、下载文件夹等:defclean_app_cache():app_cache_paths=[os.path.expanduser('~\\AppData\\Local\\Temp'),os.path.expanduser('~\\AppData\\Roaming\\Temp'),os.path.expanduser('~\\AppData\\LocalLow\\Temp'),]forcache_pathinapp_cache_paths:delete_files_in_folder(cache_path)defclean_windows_update_cache():update_cache_path=os.path.join(os.getenv('SystemRoot'),'SoftwareDistribution','Download')delete_files_in_folder(update_cache_path)defclean_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'),]forerror_report_pathinerror_report_paths:delete_files_in_folder(error_report_path)defclean_prefetch():prefetch_path=os.path.join(os.getenv('SystemRoot'),'Prefetch')delete_files_in_folder(prefetch_path)defempty_recycle_bin():subprocess.run(['PowerShell','-Command','Clear-RecycleBin','-Force'])defclean_log_files():log_file_paths=[os.path.join(os.getenv('SystemRoot'),'Logs'),os.path.join(os.getenv('SystemRoot'),'System32','LogFiles'),]forlog_file_pathinlog_file_paths:delete_files_in_folder(log_file_path)defclean_downloads():downloads_folder=os.path.expanduser('~\\Downloads')delete_files_in_folder(downloads_folder)12345678910111213141516171819202122232425262728293031323334353637383940414243执行系统命令进行额外清理我们还可以调用一些系统命令来执行特定的清理任务,比如磁盘清理工具、清理DNS缓存和删除旧版Windows更新文件:defrun_disk_cleanup():subprocess.run(['cleanmgr','/sagerun:1'])defclean_windows_old():windows_old=os.path.join(os.getenv('SystemDrive'),'Windows.old')ifos.path.exists(windows_old):shutil.rmtree(windows_old,ignore_errors=True)defclean_dns_cache():subprocess.run(['ipconfig','/flushdns'])12345678910清理注册表垃圾最后,我们可以通过访问注册表来清理一些未使用的注册表项:defclean_registry():try:withwinreg.OpenKey(winreg.HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,winreg.KEY_SET_VALUE)askey:winreg.DeleteValue(key,'SomeUnusedKey')#示例:删除未使用的注册表项exceptExceptionase:print(f"Failedtocleanregistry.Reason:{e}")123456完整脚本的执行我们将所有的清理任务整合到一个主函数main()中,并在脚本入口处调用它:importosimportshutilimportsubprocessimportwinreg#删除指定文件夹中的所有文件和文件夹defdelete_files_in_folder(folder_path):ifos.path.exists(folder_path):forfilenameinos.listdir(folder_path):file_path=os.path.join(folder_path,filename)try:ifos.path.isfile(file_path)oros.path.islink(file_path)s.unlink(file_path)elifos.path.isdir(file_path):shutil.rmtree(file_path)exceptExceptionase:print(f'Failedtodelete{file_path}.Reason:{e}')#清理Windows临时文件defclean_temp_files():temp_folders=[os.getenv('TEMP'),os.getenv('TMP'),os.path.join(os.getenv('SystemRoot'),'Temp'),]fortemp_folderintemp_folders:delete_files_in_folder(temp_folder)#清理浏览器缓存defclean_browser_cache():browser_cache_paths=[os.path.expanduser('~\\AppData\\Local\\Google\\Chrome\\UserData\\Default\\Cache'),os.path.expanduser('~\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\'),os.path.expanduser('~\\AppData\\Local\\Microsoft\\Edge\\UserData\\Default\\Cache'),]forcache_pathinbrowser_cache_paths:ifos.path.exists(cache_path):shutil.rmtree(cache_path,ignore_errors=True)#清理应用缓存defclean_app_cache():app_cache_paths=[os.path.expanduser('~\\AppData\\Local\\Temp'),os.path.expanduser('~\\AppData\\Roaming\\Temp'),os.path.expanduser('~\\AppData\\LocalLow\\Temp'),]forcache_pathinapp_cache_paths:delete_files_in_folder(cache_path)#清理Windows更新缓存defclean_windows_update_cache():update_cache_path=os.path.join(os.getenv('SystemRoot'),'SoftwareDistribution','Download')delete_files_in_folder(update_cache_path)#清理系统错误报告文件defclean_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'),]forerror_report_pathinerror_report_paths:delete_files_in_folder(error_report_path)#清理预读取文件defclean_prefetch():prefetch_path=os.path.join(os.getenv('SystemRoot'),'Prefetch')delete_files_in_folder(prefetch_path)#清理回收站defempty_recycle_bin():subprocess.run(['PowerShell','-Command','Clear-RecycleBin','-Force'])#清理日志文件defclean_log_files():log_file_paths=[os.path.join(os.getenv('SystemRoot'),'Logs'),os.path.join(os.getenv('SystemRoot'),'System32','LogFiles'),]forlog_file_pathinlog_file_paths:delete_files_in_folder(log_file_path)#删除下载文件夹中的内容defclean_downloads():downloads_folder=os.path.expanduser('~\\Downloads')delete_files_in_folder(downloads_folder)#运行磁盘清理工具defrun_disk_cleanup():subprocess.run(['cleanmgr','/sagerun:1'])#删除Windows旧版更新文件defclean_windows_old():windows_old=os.path.join(os.getenv('SystemDrive'),'Windows.old')ifos.path.exists(windows_old):shutil.rmtree(windows_old,ignore_errors=True)#清理DNS缓存defclean_dns_cache():subprocess.run(['ipconfig','/flushdns'])#清理注册表垃圾(示例)defclean_registry():try:withwinreg.OpenKey(winreg.HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,winreg.KEY_SET_VALUE)askey:winreg.DeleteValue(key,'SomeUnusedKey')#示例:删除未使用的注册表项exceptExceptionase:print(f"Failedtocleanregistry.Reason:{e}")defmain():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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134总结通过这个脚本,我们可以方便地清理Windows电脑上的各类垃圾文件,释放磁盘空间,保持系统流畅运行。这个脚本不仅可以作为个人使用,还可以根据需要进一步扩展和定制,以适应不同的清理需求。你可以将这个脚本保存为.py文件,并在需要清理系统时运行它。希望这篇教程对你有帮助!如果你对脚本有任何疑问或改进建议,欢迎留言讨论!
|
|