2017-03-07 55 views
0

有沒有一種方法可以創建一個在一小部分文件上執行的for循環? 在這種情況下,我想將子文件夾中所有圖像的1/5(最後1/5的文件)移動到其子文件夾的另一個文件夾中。我已經開始了一些,但需要幫助。用python循環部分文件

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. 
+0

是否必須是最後的20%,還是僅僅是一個例子。做一個任意的20%比較容易...你只需保留一個計數器並移動你所穿過的每個第五個文件。 –

+0

做一些文件首先說'cnt'。在循環中獲取一個計數器,每次都執行'counter + = 1'。每當'counter> 0.8 * cnt'開始移動文件'else continue'時 – abhiieor

回答

1

當然,只是切filenames相應:

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

您可能需要作出調整,如果有你所期望的具體舍入行爲。

此外,請勿使用os.system()來移動文件。使用os.rename()