2017-05-15 45 views
1

我試圖從一系列文件夾中複製最新的文件。這裏的結構:。Python - 從包含子目錄的文件夾複製最新文件

\\主機名\ DATA \文件夾1 \ * BK

\\主機名\ DATA \文件夾2 \ * BK

\\主機名\ DATA \ folder3 \ * BK

\\主機\數據\文件夾4 \ *。bk

大約有600個這些文件夾。我想將每個文件夾中最新的文件複製到一個文件夾中。有些文件夾也可能是空的。

我完全失去了這裏,並嘗試了很多沒有運氣的東西。這應該很容易,我不知道爲什麼我有這麼大的問題。

Basic代碼,

import os, shutil, sys 

source = r"\\server\data" 
dest = r"e:\dest" 

for pth in os.listdir(source): 
    if "." not in pth: 
     newsource = source + "\\" + pth + "\\" 
+0

因爲我在工作,所以我限制了我可以放在一起的模擬代碼,但是我寫了一些類似於前不久的東西。歡迎您獲取代碼並遊玩:https://github.com/DavidMetcalfe/Archive-files-older-than-set-number-days –

+0

這是一個很好的腳本,但它不適用於我。有時候有從現在開始的文件,有時候是一週之久等等。所以我只想抓取最新的文件,不管日期。 – HMan06

+0

既然你會尋找'mtime',這可能對最近的幫助很大,因爲我在提供的腳本中選擇了最老的。 http://stackoverflow.com/a/2014704/563231 –

回答

1

我寫了下面的文本編輯器,所以我不能完全測試;但是這應該會讓你獲得大部分的途徑。

import os 
import operator 

source = r"\\server\data" 
destination = r"e:\dest" 

time_dict = {} 

#Walk all of the sub directories of 'data' 
for subdir, dirs, files in os.walk(source): 
    #put each file into a dictionary with thier creation time 
    for file in os.listdir(dir): 
     time = os.path.getctime(os.path.join(subdir,file)) 
     time_dict.update({time,file}) 
    #sort the dict by time 
    sorted_dict = sorted(time_dict.items(), key=operator.itemgetter(0)) 
    #find the most recent 
    most_recent_file = next(iter(sorted_dict)) 
    #move the most recent file to the destination directory following the source folder structure 
    os.rename(source + '\\' + dir + '\\' + most_recent_file,str(destination) + '\\' + dir + '\\' + most_recent_file) 
+0

這太棒了,謝謝! – HMan06

+0

@ HMan06沒問題,很高興幫忙! –

相關問題