国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python檢測文件夾變化,并拷貝有更新的文件到對應目錄的方法

2020-02-15 23:15:03
字體:
來源:轉載
供稿:網友

檢測文件夾,拷貝有更新的文件到對應目錄 2016.5.19

親測可用,若有借鑒請修改下文件路徑;

學習python小一個月后寫的這個功能,屬于初學,若有大神路過,求代碼優化~

newcopy.py:

檢測文件夾中最后修改時間變化的文件,并拷貝復制到相應路徑下,拷貝目錄會自動檢測后輸出;測試文件夾路徑記得修改;

pyinotify.py:

借用window接口,檢測腳本所在目錄下文件夾變化(更新、刪除、添加等),輸出日志到桌面上;

# newcopy.py文件# -*- coding:UTF-8 -*-import osimport os.pathimport sysimport timeimport datetimeimport statimport difflibimport 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:", fpathdef 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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 象山县| 滨海县| 五寨县| 台东市| 当雄县| 团风县| 彭州市| 金秀| 玉林市| 富宁县| 蕉岭县| 新宁县| 鞍山市| 崇文区| 石嘴山市| 广昌县| 库车县| 南通市| 从化市| 白朗县| 腾冲县| 满城县| 贡觉县| 临桂县| 郎溪县| 石城县| 萝北县| 疏勒县| 庆云县| 军事| 宽甸| 枝江市| 扎鲁特旗| 新和县| 海淀区| 建宁县| 灵山县| 邢台县| 东乌| 南汇区| 金昌市|