Python中的意外排序会删除每个第二个文件夹

时间:2014-09-03 01:21:13

标签: arrays sorting python-2.7

我正在编写脚本来清理旧备份文件夹,并且每个第二个文件夹似乎都会在已排序的目录列表中删除。我已经弄清楚如何解决它(通过在删除之前再次排序),但不明白为什么需要解决方法。

这是第一种正确排序数组的方法(通过打印确认),然后删除每个第二个文件夹:

# Build an array of the relevant backup directories, excluding files.
BDL = [f for f in os.listdir(DST) if os.path.isdir(os.path.join(DST, f)) and f.startswith(PFX)]
BDL.sort()
print BDL

# If the number of backup directories is more than the minimum,
# delete some & decrement the array
logger.info('Deleting old backup directories.')
for f in BDL:
    if len(BDL) >= MIN:
        logger.info('Deleting %s', f)
        shutil.rmtree(DST+f)
        BDL.remove(f)

这是第二种使用'排序'并正常工作:

# Build an array of the relevant backup directories, excluding files.
BDL = [f for f in os.listdir(DST) if os.path.isdir(os.path.join(DST, f)) and f.startswith(PFX)]
BDL.sort()
print BDL

# If the number of backup directories is more than the minimum,
# delete some & decrement the array
logger.info('Deleting old backup directories.')
for f in sorted(BDL):
    if len(BDL) >= MIN:
        logger.info('Deleting %s', f)
        shutil.rmtree(DST+f)
        BDL.remove(f)

为什么有必要再次对数组进行排序?从数组中删除某些东西的行为是否会改变其余元素的顺序?

0 个答案:

没有答案