日常分享记录

winreg删除子目录

def _remove_from_registry(self, key):
import winreg

定义注册表路径

registry_path = r"Software\XXX"

def delete_key(key_path):
try:

打开注册表项以获取访问权限

registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_ALL_ACCESS)

获取子键数量

sub_keys_count, _, _ = winreg.QueryInfoKey(registry_key)

# 遍历子键并递归删除
for i in range(sub_keys_count):
    sub_key_name = winreg.EnumKey(registry_key, 0)  # 获取第一个子键
    # 递归调用删除子键
    delete_key(f"{key_path}\\{sub_key_name}")  # 递归删除
    winreg.DeleteKey(registry_key, sub_key_name)  # 删除子键
    print(f"Deleted subkey: {sub_key_name}")

# 删除父键
winreg.CloseKey(registry_key)
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path)  # 删除父键
print(f"Successfully deleted key: {key_path}")

except FileNotFoundError:
print(f"Key '{key_path}' does not exist.")
except OSError as e:
print(f"Error deleting key '{key_path}': {e}")
except Exception as e:
print("Error:", e)

运行删除逻辑

full_key_path = f"{registry_path}\{key}"
delete_key(full_key_path)


标题:winreg删除子目录
作者:badx16
地址:https://mmll.site/articles/2024/11/02/1730513829859.html

0 浏览