删除目录中除两个文件外的所有文件



我有一个删除整个目录的脚本,但我想修改它,删除除两个文件(kodi.logkodi.old.log)外的所有内容,因此需要跳过扩展名.log

我的脚本是

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

任何想法都将不胜感激。

您的if语句应该是这样的,以检查所需文件的名称是否不在文件路径中

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

或更紧凑的方式检查the_file

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

这意味着,如果文件不是kodi.log或kodi.old.log,则将其删除

您可以尝试使用递归调用。我还没能测试它,但以下应该可以工作:

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

我希望它能有所帮助!

最新更新