1. 程式人生 > >python檢測資料夾變化,並拷貝有更新的檔案到對應目錄

python檢測資料夾變化,並拷貝有更新的檔案到對應目錄

檢測資料夾,拷貝有更新的檔案到對應目錄 2016.5.19
親測可用,若有借鑑請修改下檔案路徑;
學習python小一個月後寫的這個功能,屬於初學,若有大神路過,求程式碼優化~
newcopy.py:
檢測資料夾中最後修改時間變化的檔案,並拷貝複製到相應路徑下,拷貝目錄會自動檢測後輸出;測試資料夾路徑記得修改;
pyinotify.py:
借用window介面,檢測指令碼所在目錄下資料夾變化(更新、刪除、新增等),輸出日誌到桌面上;

# newcopy.py檔案
# -*- coding:UTF-8 -*-
import os
import os.path
import
sys import time import datetime import stat import difflib import linecache, shutil # 檔案全路徑和對應最後修改時間寫入到out.txt文件中; def add_log(path): with open('out.txt','w') as f: f.close() for root , dirs, files in os.walk(path): for name in files: temp_path = os.path.join(root,name) file_name = temp_path.replace('C:/Users/Enter/Desktop/'
, '') file_time = os.stat(temp_path).st_mtime with open('out.txt','a') as f: f.write( ','.join( ['%s' % file_name , '%s\n' % file_time] ) ) f.close() # 注意時間格式轉換 #file_time = time.localtime(os.stat(root).st_mtime) #file_time=date.strftime('%Y-%m-%d %H:%M:%S')
def if_exist(): # 判斷檔案out.txt是否存在,不存在則建立 filename = 'out.txt' if os.path.exists(filename): message = 'OK, the "%s" file exists.' else: message = "Sorry, I cannot find the '%s' file..and I create it." a = open('out.txt', 'w') a.close() print message % filename # 判斷update資料夾是否存在,不存在則建立 files_name='update' if os.path.exists(files_name): message = 'OK, the "%s" file exists.' else: message = "Sorry, I cannot find the '%s' file.and I create it. " os.mkdir('update') print message % files_name # path 待比較的資料夾路徑 # 返回生成的txt(包含更新或者新增的檔案路徑)的路徑 def log_compare(path): # 先確保out.txt存在 if_exist() # 獲取out.txt檔案內容(檔案全路徑key和最後修改時間value),生成dict txt = open('out.txt', 'r').readlines() myDic = {} for row in txt: (key, value) = row.split(',') myDic[key] = value print myDic # 建立以時間命名的檔案和資料夾 setup_filename = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')) # 獲取當前時間 setup_file_path = '%s%s.txt' %('C:/Users/Enter/Desktop/update/' ,setup_filename) # 生成以當前時間命名的.txt檔案,準備寫入更新日誌 setup_file_dir = '%s%s' %('C:/Users/Enter/Desktop/update/' ,setup_filename) # 生成以當前時間命名的.txt資料夾 #判斷key,比較value值是否變化 #原始需要有一個out.txt檔案,才能比較value確定是否有更新 #執行程式時,重新遍歷一遍檔案全路徑和最後修改時間 for root , dirs, files in os.walk(path): for name in files: temp_path = os.path.join(root,name) file_name = temp_path.replace('C:/Users/Enter/Desktop/', '') time = os.stat(temp_path).st_mtime # 獲取最後修改時間 file_time = '%s\n' % time # 加%s\n是為了與out.txt裡值完全對應 if myDic.has_key(file_name) == True: if cmp(myDic[file_name], file_time): # myDic[file_name]舊最後修改時間,file_time新最後修改時間 print (file_name,file_time) # 輸出有變化的檔名及其對應的最後修改時間 # 輸出以檔案時間命名的更新日誌,生成路徑是update下 with open(setup_file_path,'a') as f: # 有更新的檔案,寫入更新日誌 f.write( '%s\n' % file_name ) f.close() else: print "add",file_name with open(setup_file_path,'a') as f: # 新增的檔案,寫入更新日誌 f.write( '%s\n' % file_name ) f.close() # 返回 當前時間,以時間命名的資料夾路徑,更新檔案路徑 return (setup_filename, setup_file_dir, setup_file_path) # 將src目錄中的內容拷貝到dest目錄 # 如果dest或者其子目錄不存在,先建立 # txt_path為更新日誌路徑,有更新的檔案才拷貝 def copy_directory(src, dest, txt_path): if not os.path.exists(txt_path): print "no file update" return # 讀更新日誌,獲取更新檔案的全路徑 txt = open(txt_path, 'r').readlines() myDic = {} myDic2 = {} for row in txt: myDic[row] = "1" tempArray = os.path.split(row) key = tempArray[0] myDic2[key] = "1" print "myDic2:", myDic2 print "dict:", myDic # 遍歷原始資料夾,得到所有檔案的全路徑 for root, dirs, files in os.walk(src): for name in files: #print "dirs:",dirs fpath = os.path.join(root, name) newroot = root newroot = newroot.replace(src, dest) # 根據檔案絕對路徑,建立將要拷貝的路徑(相對路徑),沒有則建立 #print newroot rel_dir = root.replace('C:/Users/Enter/Desktop/', '') if not os.path.exists(newroot) and myDic2.has_key(rel_dir): print "rel_dir:" , rel_dir print newroot os.makedirs(newroot) os.chmod(newroot, stat.S_IWRITE) temp = fpath temp = temp.replace(src, dest) rel_path = fpath.replace('C:/Users/Enter/Desktop/', '') # 將絕對路徑改為相對路徑,便於遍歷對比,挑出要拷貝的檔案 rel_path += '\n' if myDic.has_key(rel_path) == True: print "real_path:" , rel_path # os.mkdir(rel_path) shutil.copy(fpath, temp) print "copyfile:", fpath def main(): path_dir = 'C:/Users/Enter/Desktop/acd' path_file = 'C:/Users/Enter/Desktop/out.txt' params = log_compare(path_dir) add_log(path_dir) copy_directory(path_dir, params[1], params[2]) if __name__ == '__main__': main()
#pyinotify.py檔案
# -*- coding:UTF-8 -*-
import os
import win32file
import win32con
# #檢測當前目錄下所有檔案刪除、更新、修改等變化。更新日誌輸出到桌面。2016.5.23 copy


ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}
# Thanks to Claudio Grondi for the correct set of numbers
FILE_LIST_DIRECTORY = 0x0001
path_to_watch = "."
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)
while 1:
  #
  # ReadDirectoryChangesW takes a previously-created
  #  handle to a directory, a buffer size for results,
  #  a flag to indicate whether to watch subtrees and
  #  a filter of what changes to notify.
  #
  # NB Tim Juchcinski reports that he needed to up
  #  the buffer size to be sure of picking up all
  #  events when a large number of files were
  #  deleted at once.
  #
  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    True,
     win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
     win32con.FILE_NOTIFY_CHANGE_SIZE |
     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
     win32con.FILE_NOTIFY_CHANGE_SECURITY,
    None,
    None
  )

  #print "results:", results

  for action, file in results:
    full_filename = os.path.join (path_to_watch, file)
    print full_filename, ACTIONS.get (action, "Unknown")
    with open('C:/Users/Enter/Desktop/fileupdate.txt','a') as f:
        #str = ','.join( ['%s' % full_filename , '%s\n' % ACTIONS.get (action, "Unknown")] )
        #print str
        f.write( ','.join( ['%s' % full_filename , '%s\n' % ACTIONS.get (action, "Unknown")] ) )
        f.close()