Python實(shí)現(xiàn)安全清理各種系統(tǒng)垃圾文件
簡介
隨著時間的推移,計算機(jī)會積累大量的臨時文件、緩存文件、日志文件和其他不必要的數(shù)據(jù),這些文件不僅占用寶貴的存儲空間,還可能影響系統(tǒng)的性能。定期清理這些無用文件是系統(tǒng)維護(hù)的重要環(huán)節(jié)。本文將介紹一個實(shí)用的Python腳本——系統(tǒng)清理工具,它可以安全地清理各種系統(tǒng)垃圾文件,幫助用戶釋放存儲空間并提升系統(tǒng)性能。
功能介紹
這個系統(tǒng)清理工具具有以下核心功能:
- 多類型文件清理:支持清理臨時文件、緩存文件、日志文件、回收站等
- 跨平臺支持:支持Windows、Linux和macOS操作系統(tǒng)
- 安全清理機(jī)制:提供預(yù)覽模式,避免誤刪重要文件
- 自定義清理規(guī)則:支持自定義要清理的文件類型和目錄
- 磁盤空間統(tǒng)計:顯示清理前后磁盤空間的變化
- 日志記錄:記錄清理操作的詳細(xì)信息
- 定時任務(wù)支持:可以集成到定時任務(wù)中定期清理系統(tǒng)
- 白名單保護(hù):支持設(shè)置白名單,保護(hù)重要文件不被誤刪
應(yīng)用場景
這個工具適用于以下場景:
- 日常系統(tǒng)維護(hù):定期清理系統(tǒng)垃圾文件
- 存儲空間優(yōu)化:釋放磁盤空間,特別是存儲空間緊張時
- 性能優(yōu)化:清理過多的臨時文件以提升系統(tǒng)性能
- 系統(tǒng)準(zhǔn)備:在系統(tǒng)遷移或重裝前清理無用文件
- 故障排查:清理可能引起問題的緩存文件
- 隱私保護(hù):清理瀏覽歷史、臨時文件等隱私相關(guān)數(shù)據(jù)
報錯處理
腳本包含了完善的錯誤處理機(jī)制:
- 權(quán)限驗(yàn)證:檢查是否有足夠的權(quán)限訪問和刪除文件
- 路徑安全性檢查:驗(yàn)證要清理的路徑是否安全,防止誤刪系統(tǒng)關(guān)鍵文件
- 文件鎖定處理:處理被其他程序占用的文件
- 磁盤空間檢查:在操作前檢查是否有足夠的磁盤空間
- 異常捕獲:捕獲并處理運(yùn)行過程中可能出現(xiàn)的各種異常
- 回滾機(jī)制:在必要時提供操作回滾功能
代碼實(shí)現(xiàn)
import os
import sys
import argparse
import json
import shutil
import tempfile
from datetime import datetime, timedelta
import platform
import glob
class SystemCleaner:
def __init__(self):
self.os_type = platform.system().lower()
self.cleanup_rules = []
self.whitelist = set()
self.cleaned_files = []
self.cleaned_size = 0
self.errors = []
# 默認(rèn)清理規(guī)則
self._set_default_rules()
def _set_default_rules(self):
"""設(shè)置默認(rèn)清理規(guī)則"""
if self.os_type == 'windows':
# Windows系統(tǒng)默認(rèn)清理規(guī)則
self.cleanup_rules.extend([
{
'name': '臨時文件',
'paths': [
os.environ.get('TEMP', ''),
os.path.join(os.environ.get('SYSTEMROOT', ''), 'Temp'),
os.path.expanduser('~\\AppData\\Local\\Temp')
],
'patterns': ['*'],
'age_days': 7
},
{
'name': '回收站',
'paths': [os.path.join(drive + ':\\', '$Recycle.Bin') for drive in 'CDEFGHIJKLMNOPQRSTUVWXYZ'],
'patterns': ['*'],
'age_days': 30
},
{
'name': '瀏覽器緩存',
'paths': [
os.path.expanduser('~\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache'),
os.path.expanduser('~\\AppData\\Local\\Mozilla\\Firefox\\Profiles\\*\\cache2'),
os.path.expanduser('~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cache')
],
'patterns': ['*'],
'age_days': 7
}
])
elif self.os_type == 'linux':
# Linux系統(tǒng)默認(rèn)清理規(guī)則
self.cleanup_rules.extend([
{
'name': '臨時文件',
'paths': ['/tmp', '/var/tmp'],
'patterns': ['*'],
'age_days': 7
},
{
'name': '用戶緩存',
'paths': [os.path.expanduser('~/.cache')],
'patterns': ['*'],
'age_days': 30
},
{
'name': '日志文件',
'paths': ['/var/log'],
'patterns': ['*.log.*', '*.gz'],
'age_days': 30
}
])
elif self.os_type == 'darwin': # macOS
# macOS系統(tǒng)默認(rèn)清理規(guī)則
self.cleanup_rules.extend([
{
'name': '臨時文件',
'paths': ['/tmp', '/var/tmp'],
'patterns': ['*'],
'age_days': 7
},
{
'name': '用戶緩存',
'paths': [os.path.expanduser('~/Library/Caches')],
'patterns': ['*'],
'age_days': 30
},
{
'name': '日志文件',
'paths': [os.path.expanduser('~/Library/Logs')],
'patterns': ['*.log.*'],
'age_days': 30
}
])
def add_whitelist(self, paths):
"""添加白名單路徑"""
if isinstance(paths, str):
paths = [paths]
for path in paths:
self.whitelist.add(os.path.abspath(path))
def load_config(self, config_file):
"""從配置文件加載清理規(guī)則"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
# 加載清理規(guī)則
if 'cleanup_rules' in config:
self.cleanup_rules = config['cleanup_rules']
# 加載白名單
if 'whitelist' in config:
self.add_whitelist(config['whitelist'])
return True
except Exception as e:
self.errors.append(f"加載配置文件失敗: {e}")
return False
def save_config(self, config_file):
"""保存配置到文件"""
try:
config = {
'cleanup_rules': self.cleanup_rules,
'whitelist': list(self.whitelist)
}
with open(config_file, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
return True
except Exception as e:
self.errors.append(f"保存配置文件失敗: {e}")
return False
def format_bytes(self, bytes_value):
"""格式化字節(jié)單位"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_value < 1024.0:
return f"{bytes_value:.2f} {unit}"
bytes_value /= 1024.0
return f"{bytes_value:.2f} PB"
def is_safe_path(self, path):
"""檢查路徑是否安全"""
# 檢查是否在白名單中
abs_path = os.path.abspath(path)
for whitelist_path in self.whitelist:
if abs_path.startswith(whitelist_path):
return False
# 檢查是否是系統(tǒng)關(guān)鍵目錄
critical_paths = []
if self.os_type == 'windows':
system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows')
critical_paths = [system_root, 'C:\\Program Files', 'C:\\Program Files (x86)']
elif self.os_type in ['linux', 'darwin']:
critical_paths = ['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/etc', '/boot']
for critical_path in critical_paths:
if abs_path.startswith(critical_path):
return False
return True
def get_file_age(self, filepath):
"""獲取文件年齡(天數(shù))"""
try:
file_time = os.path.getmtime(filepath)
file_datetime = datetime.fromtimestamp(file_time)
age = datetime.now() - file_datetime
return age.days
except:
return 0
def match_patterns(self, filename, patterns):
"""檢查文件名是否匹配模式"""
for pattern in patterns:
if glob.fnmatch.fnmatch(filename, pattern):
return True
return False
def scan_files(self, rule):
"""掃描符合規(guī)則的文件"""
found_files = []
for path in rule['paths']:
if not path or not os.path.exists(path):
continue
try:
# 遞歸遍歷目錄
for root, dirs, files in os.walk(path):
# 跳過隱藏目錄
dirs[:] = [d for d in dirs if not d.startswith('.')]
for filename in files:
# 跳過隱藏文件
if filename.startswith('.'):
continue
filepath = os.path.join(root, filename)
# 檢查文件是否匹配模式
if not self.match_patterns(filename, rule['patterns']):
continue
# 檢查文件年齡
if 'age_days' in rule:
file_age = self.get_file_age(filepath)
if file_age < rule['age_days']:
continue
# 檢查路徑安全性
if not self.is_safe_path(filepath):
continue
# 獲取文件大小
try:
file_size = os.path.getsize(filepath)
except:
file_size = 0
found_files.append({
'path': filepath,
'size': file_size,
'age': self.get_file_age(filepath)
})
except Exception as e:
self.errors.append(f"掃描目錄 {path} 時出錯: {e}")
return found_files
def preview_cleanup(self):
"""預(yù)覽清理操作"""
print("系統(tǒng)清理預(yù)覽")
print("=" * 60)
print(f"操作系統(tǒng): {self.os_type}")
print()
total_files = 0
total_size = 0
for rule in self.cleanup_rules:
print(f"清理規(guī)則: {rule['name']}")
files = self.scan_files(rule)
if files:
rule_size = sum(f['size'] for f in files)
print(f" 發(fā)現(xiàn)文件: {len(files)} 個")
print(f" 預(yù)計釋放: {self.format_bytes(rule_size)}")
total_files += len(files)
total_size += rule_size
# 顯示前10個文件作為示例
print(" 文件示例:")
for i, file_info in enumerate(files[:10]):
print(f" {file_info['path']} ({self.format_bytes(file_info['size'])}, {file_info['age']}天)")
if len(files) > 10:
print(f" ... 還有 {len(files) - 10} 個文件")
else:
print(" 未發(fā)現(xiàn)符合條件的文件")
print()
print(f"總計:")
print(f" 文件數(shù)量: {total_files}")
print(f" 預(yù)計釋放: {self.format_bytes(total_size)}")
return total_files, total_size
def perform_cleanup(self, dry_run=True):
"""執(zhí)行清理操作"""
print(f"{'預(yù)覽' if dry_run else '執(zhí)行'}系統(tǒng)清理")
print("=" * 60)
self.cleaned_files = []
self.cleaned_size = 0
cleaned_count = 0
for rule in self.cleanup_rules:
print(f"處理規(guī)則: {rule['name']}")
files = self.scan_files(rule)
for file_info in files:
filepath = file_info['path']
filesize = file_info['size']
if dry_run:
print(f" 將刪除: {filepath} ({self.format_bytes(filesize)})")
else:
try:
os.remove(filepath)
print(f" 已刪除: {filepath}")
self.cleaned_files.append(filepath)
self.cleaned_size += filesize
cleaned_count += 1
except Exception as e:
error_msg = f"刪除文件 {filepath} 失敗: {e}"
print(f" 錯誤: {error_msg}")
self.errors.append(error_msg)
print()
if not dry_run:
print(f"清理完成:")
print(f" 刪除文件: {cleaned_count} 個")
print(f" 釋放空間: {self.format_bytes(self.cleaned_size)}")
return cleaned_count, self.cleaned_size
def clean_empty_dirs(self, dry_run=True):
"""清理空目錄"""
print(f"{'預(yù)覽' if dry_run else '執(zhí)行'}空目錄清理")
print("=" * 60)
cleaned_dirs = 0
for rule in self.cleanup_rules:
for path in rule['paths']:
if not path or not os.path.exists(path):
continue
try:
for root, dirs, files in os.walk(path, topdown=False):
# 檢查目錄是否為空
if not os.listdir(root):
if dry_run:
print(f" 將刪除空目錄: {root}")
else:
try:
os.rmdir(root)
print(f" 已刪除空目錄: {root}")
cleaned_dirs += 1
except Exception as e:
error_msg = f"刪除目錄 {root} 失敗: {e}"
print(f" 錯誤: {error_msg}")
self.errors.append(error_msg)
except Exception as e:
self.errors.append(f"遍歷目錄 {path} 時出錯: {e}")
if not dry_run:
print(f"空目錄清理完成: {cleaned_dirs} 個目錄")
return cleaned_dirs
def generate_report(self):
"""生成清理報告"""
report = []
report.append("=" * 80)
report.append("系統(tǒng)清理報告")
report.append("=" * 80)
report.append(f"清理時間: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append(f"操作系統(tǒng): {self.os_type}")
report.append("")
# 清理統(tǒng)計
report.append("清理統(tǒng)計:")
report.append(f" 刪除文件: {len(self.cleaned_files)} 個")
report.append(f" 釋放空間: {self.format_bytes(self.cleaned_size)}")
report.append("")
# 清理的文件列表
if self.cleaned_files:
report.append("已清理的文件:")
report.append("-" * 50)
for filepath in self.cleaned_files:
report.append(f" {filepath}")
report.append("")
# 錯誤信息
if self.errors:
report.append("錯誤信息:")
report.append("-" * 50)
for error in self.errors[:20]: # 只顯示前20個錯誤
report.append(f" {error}")
if len(self.errors) > 20:
report.append(f" ... 還有 {len(self.errors) - 20} 個錯誤")
report.append("")
report.append("=" * 80)
return "\n".join(report)
def save_report(self, filename):
"""保存報告到文件"""
try:
report = self.generate_report()
with open(filename, 'w', encoding='utf-8') as f:
f.write(report)
print(f"報告已保存到: {filename}")
return True
except Exception as e:
print(f"保存報告時出錯: {e}")
return False
def create_sample_config():
"""創(chuàng)建示例配置文件"""
config = {
"cleanup_rules": [
{
"name": "自定義臨時文件",
"paths": ["/custom/temp/path"],
"patterns": ["*.tmp", "*.temp"],
"age_days": 7
}
],
"whitelist": [
"/important/files/not/to/delete"
]
}
try:
with open('cleaner_config.json', 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
print("示例配置文件已創(chuàng)建: cleaner_config.json")
return True
except Exception as e:
print(f"創(chuàng)建示例配置文件時出錯: {e}")
return False
def main():
parser = argparse.ArgumentParser(description="系統(tǒng)清理工具")
parser.add_argument("-c", "--config", help="配置文件路徑")
parser.add_argument("-p", "--preview", action="store_true", help="預(yù)覽模式,不實(shí)際刪除文件")
parser.add_argument("-o", "--output", help="保存報告到文件")
parser.add_argument("--create-config", action="store_true", help="創(chuàng)建示例配置文件")
parser.add_argument("--clean-empty-dirs", action="store_true", help="清理空目錄")
parser.add_argument("--add-whitelist", action="append", help="添加白名單路徑")
args = parser.parse_args()
# 創(chuàng)建示例配置文件
if args.create_config:
create_sample_config()
return
try:
cleaner = SystemCleaner()
# 加載配置文件
if args.config:
if not cleaner.load_config(args.config):
print("加載配置文件失敗")
sys.exit(1)
# 添加白名單
if args.add_whitelist:
cleaner.add_whitelist(args.add_whitelist)
# 預(yù)覽或執(zhí)行清理
if args.preview:
cleaner.preview_cleanup()
else:
# 執(zhí)行清理
cleaned_count, cleaned_size = cleaner.perform_cleanup(dry_run=False)
# 清理空目錄
if args.clean_empty_dirs:
cleaner.clean_empty_dirs(dry_run=False)
# 生成報告
if args.output:
cleaner.save_report(args.output)
else:
print(cleaner.generate_report())
except KeyboardInterrupt:
print("\n\n用戶中斷操作")
except Exception as e:
print(f"程序執(zhí)行出錯: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
使用方法
基本使用
# 創(chuàng)建示例配置文件 python system_cleaner.py --create-config # 預(yù)覽清理操作(不實(shí)際刪除文件) python system_cleaner.py --preview # 執(zhí)行清理操作 python system_cleaner.py # 使用配置文件 python system_cleaner.py -c cleaner_config.json # 保存清理報告 python system_cleaner.py -o cleanup_report.txt # 清理空目錄 python system_cleaner.py --clean-empty-dirs # 添加白名單路徑 python system_cleaner.py --add-whitelist /important/data --preview
配置文件示例
創(chuàng)建的示例配置文件 cleaner_config.json 內(nèi)容如下:
{
"cleanup_rules": [
{
"name": "自定義臨時文件",
"paths": ["/custom/temp/path"],
"patterns": ["*.tmp", "*.temp"],
"age_days": 7
}
],
"whitelist": [
"/important/files/not/to/delete"
]
}
命令行參數(shù)說明
-c, --config: 配置文件路徑-p, --preview: 預(yù)覽模式,不實(shí)際刪除文件-o, --output: 保存報告到指定文件--create-config: 創(chuàng)建示例配置文件--clean-empty-dirs: 清理空目錄--add-whitelist: 添加白名單路徑(可多次使用)
使用示例
預(yù)覽清理操作:
python system_cleaner.py --preview
執(zhí)行清理并保存報告:
python system_cleaner.py -o cleanup_$(date +%Y%m%d).txt
使用自定義配置:
python system_cleaner.py -c my_cleaner_config.json --preview
添加白名單并清理:
python system_cleaner.py --add-whitelist /home/user/important --clean-empty-dirs
總結(jié)
這個系統(tǒng)清理工具提供了一個安全、靈活的系統(tǒng)清理解決方案,能夠跨平臺清理各種類型的垃圾文件。它具有預(yù)覽模式、白名單保護(hù)、自定義規(guī)則等安全特性,可以有效防止誤刪重要文件。工具支持配置文件管理,便于定制清理規(guī)則,適用于日常系統(tǒng)維護(hù)、存儲空間優(yōu)化和性能提升等多種場景。通過定期使用這個工具,用戶可以保持系統(tǒng)的清潔和高效運(yùn)行。
以上就是Python實(shí)現(xiàn)安全清理各種系統(tǒng)垃圾文件的詳細(xì)內(nèi)容,更多關(guān)于Python清理系統(tǒng)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python 推導(dǎo)表達(dá)式的幾種方法實(shí)現(xiàn)
推導(dǎo)表達(dá)式是Python中一種遍歷序列并創(chuàng)建指定類型對象的方法,常用的推導(dǎo)表達(dá)式有:列表表達(dá)式、生成器表達(dá)式、字典表達(dá)式、集合表達(dá)式等,下面就來介紹一下2025-06-06
python opencv根據(jù)顏色進(jìn)行目標(biāo)檢測的方法示例
這篇文章主要介紹了python opencv根據(jù)顏色進(jìn)行目標(biāo)檢測的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
Python代碼實(shí)現(xiàn)http/https代理服務(wù)器的腳本
這篇文章主要介紹了Python代碼做出http/https代理服務(wù)器,啟動即可做http https透明代理使用,通過幾百行代碼做出http/https代理服務(wù)器代碼片段,需要的朋友可以參考下2019-08-08
帶你用Python實(shí)現(xiàn)Saga 分布式事務(wù)的方法
在這篇文章里,我們介紹了 SAGA 的理論知識,也通過一個例子,完整給出了編寫一個 SAGA 事務(wù)的過程,涵蓋了正常成功完成,異常情況,以及成功回滾的情況,需要的朋友參考下吧2021-09-09
python QT界面關(guān)閉線程池的線程跟隨退出完美解決方案
這篇文章主要介紹了python QT界面關(guān)閉,線程池的線程跟隨退出解決思路方法,本文給大家分享兩種方法結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11
使用Python實(shí)現(xiàn)調(diào)整Excel中的行列順序
調(diào)整Excel?行列順序指的是改變工作表中行或列的位置,以便更好地展示和分析數(shù)據(jù),本文將介紹如何通過Python高效地調(diào)整Excel?行列順序,感興趣的可以了解下2025-01-01

