使用python循环文件的一小部分

时间:2017-03-07 16:40:53

标签: python for-loop

有没有办法创建一个执行超过一小部分文件的for循环? 在这种情况下,我想将子文件夹中所有图像的1/5(最后1/5文件)移动到具有其子文件夹的另一个文件夹。我已经开始了一些,但需要帮助。

import os

path = 'pictures/'
outpath = 'oldpictures/'

for root, dirs, filenames in os.walk(path):
    new_dir = root.replace(path, outpath, 1)
    if not os.path.exists(new_dir):
        os.mkdir(new_dir)
    for filename in filenames: #Is it here that I can loop over the last fraction of all the files somehow?
        os.system(mv {0} {1}.format(filename, new_dir)) #Dunno if this is the best way either or if it is possible.

1 个答案:

答案 0 :(得分:1)

当然,只需相应地切片filenames

# Loop through the last ~1/5 of filenames
for filename in filenames[4*len(filenames)//5:]:
    ...

如果您有预期的特定舍入行为,则可能需要进行调整。

另外,请勿使用os.system()移动文件。使用os.rename()