Delete all subfolders and files with exception
#1
I'm trying to figure out a way to delete all subfolders and files within userdata except a certain folder. I found this code but I'm not sure how to add an exception to it. Anyone have an idea?

Code:
TARGET = xbmc.translatePath(
        'special://home/userdata'
        )
    path = TARGET
    folder = TARGET
    if os.path.exists(TARGET):
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path): shutil.rmtree(file_path)
                donevalue = '1'
            except Exception, e:
                print e
Reply
#2
Code:
saveFolders = [""]
    text_file_path = os.path.join(myUserdataPath, "SaveFolders.txt")
    open_file = open(text_file_path, 'r')
    with open_file as reader:
        saveFolders = reader.read().splitlines()
        open_file.close()
        
    if os.path.exists(addonPath)==True:
        for d in os.listdir(addonPath):
            if d not in saveFolders:
                try: os.remove(os.path.join(addonPath,d))
                except: shutil.rmtree(os.path.join(addonPath,d))

now you can create a txt file within your addon folder called "SaveFolders.txt" and enter all the folders you would like to save
enter 1 folder per line
e.g
addon_data
Database
etc...

this way you dont have to keep hard coding the folder names in the code
Reply
#3
I had to change a few things but this works perfect! Thank you bajwamar! Smile
Reply
#4
do share the changes for others to learn
Reply

Logout Mark Read Team Forum Stats Members Help
Delete all subfolders and files with exception0