標籤:移動 覆蓋 目錄 合并
#encoding: utf-8#author: walker#date: 2017-06-15#summary: 自訂檔案夾處理函數,適用於python3.5+import osimport shutilimport win32com.client#清空目錄def ClearDir(dir): print(‘ClearDir ‘ + dir + ‘...‘) for entry in os.scandir(dir): if entry.name.startswith(‘.‘): continue if entry.is_file(): os.remove(entry.path) #刪除檔案 else: shutil.rmtree(entry.path) #刪除目錄 #擷取目錄大小#不存在或空目錄都返回0def GetDirSize(pathdir): if not os.path.exists(pathdir): print(‘Warning: not exists %s‘ % pathdir) return 0 fso = win32com.client.Dispatch(‘Scripting.FileSystemObject‘) folder = fso.GetFolder(pathdir) return folder.Size ‘‘‘# 合并來源目錄到目標目錄,來源目錄中的空目錄不會被處理# src_dir: 來源目錄# dst_dir: 目標目錄# reserve_src: 是否保留來源資料# override: 是否覆蓋目標目錄中的檔案‘‘‘def MergeDir(src_root, dst_root, reserve_src=True, override=True): if (not os.path.exists(src_root)) or (not os.path.exists(dst_root)): #目錄不存在 raise FileNotFoundError for parent, dirnames, filenames in os.walk(src_root): for filename in filenames: src_file = os.path.join(parent, filename) dst_file = os.path.join(dst_root, src_file[len(src_root)+1:]) if os.path.exists(dst_file) and (not override): #如果目標檔案存在且不能被覆蓋 continue dst_dir = os.path.dirname(dst_file) if not os.path.exists(dst_dir): os.makedirs(dst_dir) if reserve_src : #保留來源資料 shutil.copyfile(src_file, dst_file) #會覆蓋目標檔案 else: shutil.move(src_file, dst_file) if not reserve_src: shutil.rmtree(src_root) #刪除源根目錄
相關連結:
1、pywin32下載
2、Python檔案(夾)基本操作
*** walker ***
本文出自 “walker的流水賬” 部落格,請務必保留此出處http://walkerqt.blog.51cto.com/1310630/1936982
自訂檔案夾處理函數(Python)