0

我有一个删除整个目录的脚本,但我想修改它以删除除两个文件(kodi.log和)之外的所有内容,因此需要跳过kodi.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

任何想法将不胜感激。

4

2 回答 2

1

您的 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 则将其删除

于 2016-04-10T21:24:04.013 回答
0

您可以尝试使用递归调用。我无法对其进行测试,但以下应该可以工作:

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

我希望它有帮助!

于 2016-04-10T21:08:10.730 回答