0

I have a script that removes an entire directory, but I would like to amend it to delete everything with the exception of two files (kodi.log and kodi.old.log), so the extension .log needs to be skipped.

The script I have is

TEMP = xbmc.translatePath(
    'special://home/temp'
)
folder = TEMP
if os.path.exists(TEMP):
    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

Any ideas would be greatly appreciated.

Jongware
  • 22,200
  • 8
  • 54
  • 100

2 Answers2

1

your if statement should be like this to check if the name of your desired file is not in the filepath

if os.path.isfile(file_path) and 'kodi.log' not in file_path and 'kodi.old.log' not in file_path:
    # delete the file

or a more compact way check the_file

if the_file not in ['kodi.log', 'kodi.old.log']:
    # delete the file

this means if the file is not kodi.log or kodi.old.log then delete it

danidee
  • 9,298
  • 2
  • 35
  • 55
0

You can try to use recursive calls. I haven't been able to test it but the following should work:

TEMP = xbmc.translatePath(
    'special://home/temp'
)
folder = TEMP
def remove_directory(folder):
    if os.path.exists(folder):
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            if file_path in ("kodi.log", "kodi.old.log"):
                continue
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    remove_directory(file_path)
                    donevalue = '1'
            except Exception, e:
                print e

I hope it helps!

Xiflado
  • 176
  • 10