[Python] 纯文本查看 复制代码
import os
import re
import string
import shutil
import winreg
from time import sleep
from pathlib import Path
import configparser
def get_disklist():
disk_list = []
for c in string.ascii_uppercase:
disk = c + ':'
if os.path.isdir(disk):
disk_list.append(c)
Path(disk_list[-1]+':/wx_path.ini').touch()
return disk_list[-1]
# 记录一下所有垃圾的总大小
total_trash_size = 0
disk_data = get_disklist()
def get_reg_dir(software):
if software == "微信":
try:
string = r'SOFTWARE\Tencent\WeChat'
handle = winreg.OpenKey(winreg.HKEY_CURRENT_USER, string, 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ))
location, _type = winreg.QueryValueEx(handle, "FileSavePath")
return location
except :
return False
elif software == "企业微信":
try:
string = r'SOFTWARE\Tencent\WXWork'
handle = winreg.OpenKey(winreg.HKEY_CURRENT_USER, string, 0, (winreg.KEY_WOW64_64KEY + winreg.KEY_READ))
location, _type = winreg.QueryValueEx(handle, "DataLocationPath")
return location
except :
return False
def get_software_dir(software):
if software == "微信":
if os.path.exists(disk_data+':/wx_path.ini'):
try:
cf = configparser.ConfigParser()
cf.read(disk_data+':/wx_path.ini',encoding='utf-8')
wx_path = cf.get("weixin","wx_path")
return Path(wx_path)
except Exception as e:
print(e)
if Path(Path.home() / "Documents" / "WeChat Files").is_file():
wx_path = Path(Path.home() / "Documents" / "WeChat Files")
return Path(wx_path)
if os.path.exists(Path.home() /'AppData'/'Roaming'/'Tencent'/'WeChat'/'All Users'/'config'/'3ebffe94.ini'):
try:
with open(Path.home() /'AppData'/'Roaming'/'Tencent'/'WeChat'/'All Users'/'config'/'3ebffe94.ini', "r") as f: # 打开文件
wx_path = Path(str(f.read())+"/WeChat Files") # 读取文件
if os.path.exists(wx_path):
return wx_path
except Exception as e:
print(e)
if os.path.exists(Path.home() /'AppData'/'Roaming'/'Tencent'/'WeChat'/'All Users'/'config'/'b928cd74.ini'):
try:
with open(Path.home() /'AppData'/'Roaming'/'Tencent'/'WeChat'/'All Users'/'config'/'b928cd74.ini', "r") as f: # 打开文件
wx_path = Path(str(f.read())+"/WeChat Files") # 读取文件
if os.path.exists(wx_path):
return wx_path
except Exception as e:
print(e)
if get_reg_dir("微信"):
return Path(get_reg_dir("微信"))
wx_path = Path(input("未找到微信缓存目录!请手动输入:"))
try:
os.chdir(disk_data+':/')
cf = configparser.ConfigParser()
cf.add_section("weixin")
cf.set("weixin","wx_path",str(wx_path))
with open(disk_data+':/wx_path.ini',"a") as f:
cf.write(f)
except Exception as e:
print(e)
return Path(str(wx_path))
else:
wx_path = Path(input("未找到微信缓存目录!请手动输入:"))
try:
Path(disk_data+':/wx_path.ini').touch()
os.chdir(disk_data+':/')
cf = configparser.ConfigParser()
cf.add_section("weixin")
cf.set("weixin","wx_path",str(wx_path))
with open(disk_data+':/wx_path.ini',"a") as f:
cf.write(f)
except Exception as e:
print(e)
return Path(str(wx_path))
elif software == "企业微信":
if os.path.exists(disk_data+':/wx_path.ini'):
try:
cf = configparser.ConfigParser()
cf.read(disk_data+':/wx_path.ini',encoding='utf-8')
qywx_path = cf.get("qyweixin","qywx_path")
return Path(qywx_path)
except Exception as e:
print(e)
if Path(Path.home() / "Documents" / "WXWork").is_file():
wkchat_dir = Path(Path.home() / "Documents" / "WXWork")
return wkchat_dir
if get_reg_dir("企业微信"):
return Path(get_reg_dir("企业微信"))
qywx_path = Path(input("未找到企业微信缓存目录!请手动输入:"))
try:
os.chdir(disk_data+':/')
cf = configparser.ConfigParser()
cf.add_section("qyweixin")
cf.set("qyweixin","qywx_path",str(qywx_path))
with open(disk_data+':/wx_path.ini',"a") as f:
cf.write(f)
except Exception as e:
print(e)
return Path(qywx_path)
else:
qywx_path = Path(input("未找到微信缓存目录!请手动输入:"))
try:
Path(disk_data+':/wx_path.ini').touch()
os.chdir(disk_data+':/')
cf = configparser.ConfigParser()
cf.add_section("qyweixin")
cf.set("qyweixin","qywx_path",str(qywx_path))
with open(disk_data+':/wx_path.ini',"a") as f:
cf.write(f)
except Exception as e:
print(e)
return Path(qywx_path)
def remove_wxtrash():
"""删除微信的所有缓存"""
global total_trash_size
# 找到微信的存储目录
wechat_dir = get_software_dir("微信")
print(wechat_dir)
# 记录所有垃圾文件和文件夹的路径,用来之后进行删除
trash_list = []
print('开始扫描微信的缓存文件...')
print('=' * 30)
# All Users 目录存储了所有登录过的用户使用过的头像
trash_list.extend(find_trash(Path(os.environ.get('USERPROFILE') +'/AppData/Local/Temp'), title='系统缓存文件'))
trash_list.extend(find_trash(wechat_dir / "All Users", '*', '已登录过用户的头像图片'))
# Applet 目录存储了所有小程序的缓存
trash_list.extend(find_trash(wechat_dir / "Applet", '*', '公用小程序缓存'))
# 获取所有登录过的用户产生的缓存文件
for d in wechat_dir.iterdir():
if d.name not in ['Applet', 'All Users']:
try:
name = re.split("\\\\",str(d))[-1]
print(f'{name} 的目录下,共发现:')
except :
pass
trash_list.extend(find_trash(d / 'Applet', title='用户小程序缓存',indent=1))
# Attachment,Backup,BackupFiles,CustomEmotions 都是空的
# Data 不知道干什么用的,但是不大,先不删了
# FavTemp 不知道是什么,但是应该没用,可以删
trash_list.extend(find_trash(d / 'FavTemp', title='其他缓存',indent=1))
# 表情包文件缓存
trash_list.extend(find_trash(d / 'CustomEmoV1', title='表情文件缓存'))
trash_list.extend(find_trash(d / 'ResUpdate', title='更新缓存文件',indent=1))
trash_list.extend(find_trash(d / 'ResUpdateV2', title='其他垃圾文件',indent=1))
trash_list.extend(find_trash(d / 'FileStorage' , title='缓存文件',indent=1))
print('=' * 30)
print(f'总垃圾大小:{total_trash_size:.3f} MB')
# print('请注意,以上垃圾包含所有下载(点开)过的图片、视频、文本文件,请谨慎删除!')
# user_input = input('是否清除全部垃圾?y(es)/n(o) > ')
# if user_input.lower() not in ['y', 'yes']:
# return
print('开始清理垃圾...')
for p in trash_list:
if not remove_file_or_folder(p):
total_trash_size -= get_size(p)
print(f'本次共清理微信垃圾 {total_trash_size:.3f} MB')
def remove_wktrash():
"""删除企业微信的所有缓存"""
global total_trash_size
# 找到微信的存储目录
wkchat_dir = get_software_dir("企业微信")
print(wkchat_dir)
# 记录所有垃圾文件和文件夹的路径,用来之后进行删除
trash_list = []
print('开始扫描企业微信的缓存文件...')
print('=' * 30)
# All Users 目录存储了所有登录过的用户使用过的头像
for d in wkchat_dir.iterdir():
try:
name = re.split("\\\\",str(d))[-1]
print(f'{name} 的目录下,共发现:')
except :
pass
trash_list.extend(find_trash(d / "Avator", '*', '已登录过用户的头像图片',indent=1))
# Applet 目录存储了所有小程序的缓存
trash_list.extend(find_trash(d / "Cache", '*', '缓存',indent=1))
trash_list.extend(find_trash(d / "Emotion", '*', '表情包',indent=1))
trash_list.extend(find_trash(d / "WeDrive", '*', '网盘文件',indent=1))
print('=' * 30)
print(f'总垃圾大小:{total_trash_size:.3f} MB')
# print('请注意,以上垃圾包含所有下载(点开)过的图片、视频、文本文件,请谨慎删除!')
# user_input = input('是否清除全部垃圾?y(es)/n(o) > ')
# if user_input.lower() not in ['y', 'yes']:
# return
print('开始清理垃圾...')
for p in trash_list:
if not remove_file_or_folder(p):
total_trash_size -= get_size(p)
print(f'本次共清理企业微信垃圾 {total_trash_size:.3f} MB')
def find_trash(d: Path, glob='*', title='缓存', indent=0):
"""获取某个垃圾文件夹的信息"""
if not d.exists():
return []
global total_trash_size
total_size = 0
trash_list = []
for p in d.glob(glob):
total_size += get_size(p)
trash_list.append(p)
# 如果传入 title 为空,则不输出信息,仅记录垃圾文件的路径
if not title:
return trash_list
# 开头的缩进
if indent > 0:
title = '\t' * indent + title
# 输出信息
print(f'{title}:{total_size:.3f} MB')
total_trash_size += total_size
return trash_list
def remove_file_or_folder(p: Path):
"""删除文件或文件夹"""
try:
if p.is_file():
p.unlink()
elif p.is_dir():
shutil.rmtree(p.absolute())
else:
# 见鬼去吧
pass
return True
except:
print(f'无法删除 {p.absolute()}')
return False
def get_size(p: Path):
"""获取一个文件或文件夹的大小"""
# 如果是文件
if p.is_file():
return p.stat().st_size / 1048576 # 以 MB 为单位
# 如果是文件夹
elif p.is_dir():
# 获取其下所有文件的大小之和
return sum([get_size(f) for f in p.rglob('*') if f.is_file()])
# 我不知道除了文件和文件夹以外还有别的什么类型,但是如果有,让它见鬼去吧
return 0
if __name__ == "__main__":
remove_wxtrash()
sleep(5)
remove_wktrash() sleep(20)