2016-12-07 5 views
0

過去24時間の新しいファイルまたは更新されたファイルのみを新しいフォルダに移動するスクリプトを作成しようとしています。これまで一般的にファイルを移動するためのスクリプトを作成しましたが、どのようなリードや提案も高く評価されます。新しいファイルまたは更新されたファイルのみを移動する方法は?

import os, shutil 

source = os.listdir('C:\Users\Student\Desktop\FolderA') 
destination = 'C:\Users\Student\Desktop\FolderB' 

os.chdir('C:\Users\Student\Desktop\FolderA') 

for files in os.listdir("C:\Users\Student\Desktop\FolderA"): 
    if files.endswith(".txt"): 
     src = os.path.join("C:\Users\Student\Desktop\FolderA",files) 
     dst = os.path.join(destination,files) 
     shutil.move(src,dst) 
+0

ここでは、ファイルの作成日時を得るのを助けることができ質問です:http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-inは-python 作成日で、現在の日付と比較することができます。 –

+2

(1)同じコードでハードコーディングされたリテラル 'FolderA'パスを4回繰り返さないでください。 (2) 'os.stat(filename).st_mtime'を使って、ファイルの最終更新タイムスタンプを取得します。 – jez

+0

[Pythonでファイルを最後に修正した時刻を取得するにはどうすればよいですか?](http://stackoverflow.com/questions/375154/how-do-i-get-the-time-a-file-was -last-modified-in-python) –

答えて

0

私は解決策を見つけたと信じていますが、皆さんの意見を教えてください。

# copy files from folder_a to folder_b 
# if the files in folder_a have been modified within the past 24 hours 
# copy them to folder_b 
# 


import shutil 
import os 
from os import path 
import datetime 
from datetime import date, time, timedelta 


def file_has_changed(fname): 
# print 'in file_has_changed with file : %s' % fname 
# print str(path.getmtime(fname)) 

# get file modified time 
    file_m_time = datetime.datetime.fromtimestamp(path.getmtime(fname)) 

# print datetime.datetime.now() 
# print file_m_time 

    #get the delta between today and filed mod time 
    td = datetime.datetime.now() - file_m_time 

# print td 
# print 'days : %d' % td.days 

# file can be archived if mod within last 24 hours 
    if td.days == 0: 
    global ready_to_archive 
    ready_to_archive = ready_to_archive + 1 
    return True 
    else: return False 



def main(): 
    global ready_to_archive 
    global archived 
    ready_to_archive, archived = 0, 0 

    # src = "c:\users\gail\desktop\foldera" 
    # dst = "c:\users\gail\desktop\folderb" 

    for fname in os.listdir('c:\users\gail\Desktop\FolderA'): 

    src_fname = 'c:\users\gail\Desktop\FolderA\%s' % fname 

    if file_has_changed(src_fname):  
     dst_fname = 'c:\users\gail\Desktop\FolderB\%s' % fname 
     dst_folder = 'c:\users\gail\Desktop\FolderB' 


     try: 
     shutil.copy2(src_fname, dst_folder) 
     global archived; 
     archived = archived + 1 
     # print 'Copying file : %s ' % (src_fname) 
     # print '  To loc : %s ' % (dst_fname) 
     except IOError as e: 
     print 'could not open the file: %s ' % e 



if __name__ == "__main__": 

    main() 

    print '****** Archive Report for %s ******' % datetime.datetime.now() 
    print '%d files ready for archiving ' % ready_to_archive 
    print '%d files archived' % archived 
    print '****** End of Archive Report ******' 
関連する問題