Remove old snap data for uninstalled snap apps with Python

Snaps do have a purge argument but I always forget to use it. I wrote a script in Python to help with my laziness. This will only remove snap data for apps that have been uninstalled. If you want to keep the data and configs for some apps you will need to include the name in preserve list. This could be altered to handle Flatpak apps as well.

#!/usr/bin/env python3

import os
import shutil
import subprocess as sp

def get_installed_snaps():
    '''Collect installed snaps.'''
    snap_names = []
    result = sp.run(["snap", "list"], capture_output=True, text=True, check=True)
    if not result.stderr:
        raw_list =  result.stdout.split('\n')
        for app in raw_list:
            if not app: continue
            snap_names.append(app.split()[0].strip().lower())
    return snap_names

def get_snap_folders():
    '''Collect all snap app folders.'''
    snap_confs = {}
    home = os.path.join(os.environ['HOME'],"snap")
    for folder in os.listdir(home):
        if not folder.strip(): continue
        snap_confs[folder]=os.path.join(home,folder.strip().lower())
    return snap_confs

# User defined.
preserve = ["some_app_name", "another"] # Make sure the name is lowercase and matches exactly what is found.
do_delete = False

# Main
installed = get_installed_snaps()
configs = get_snap_folders()

for appnm,apppth in configs.items():

    if appnm not in installed:
    
        if appnm.lower() in preserve: 
            continue
            
        print('removing ', apppth)

        if do_delete:
            shutil.rmtree(apppth)