使用Python來比較資料夾並提取差異部分

suzhouclark發表於2000-01-01
使用Python來比較資料夾並提取差異部分[@more@]

下面的指令碼可以在Python24裡很好地執行,在其他版本里沒有,但用的都是基本功能,應該沒有什麼問題。

程式碼裡的PathA是全的資料的資料夾,PathB是不全的資料的資料夾,PathC是個新的空目錄,指令碼執行完後就把PathA中有且pathB中沒有的檔案和目錄都寫到PathC裡了,還可以保持原來的目錄結構,速度和正確性都很令人滿意。

因為是急用的程式碼,所以寫得不很簡潔,也不是很規範,在此留志,一方面供自己以後參考,另一方面也提供給需要使用Python進行檔案和目錄操作的兄弟們共同參考。

# coding: GB2312

#系統模組
import sys
import os
import shutil
#用於檔案查詢的模組
from os.path import walk, join, normpath

#這個是完整的資料夾
PathA = "F:FullData"
#這個是缺檔案的資料夾
PathB = "F:IncomplData"

#這個是目標資料夾
PathC = "F:DiffData"

#============================================================
#這個函式是用來遞迴處理PathA,對PathA裡的每個檔案和資料夾在PathB中找是否有對應的檔案或資料夾
#若找不到,則在PathC中建立目錄並複製檔案
#複製檔案時使用了shutil模組的copy2函式,以保留檔案原來的建立時間和最後更新時間
def visit(arg, dirname, names):
#把目錄列印出來,以監視進度
print dirname

#得到路徑名後,把前面的主路徑名去掉
dir=dirname.replace(PathA,"")

dirnameB = os.path.join(PathB,dir)
dirnameC = os.path.join(PathC,dir)

if os.path.isdir(dirnameB):
#若PathB裡存在對應的資料夾,再逐個檔案判斷是否存在
for file in names:
if os.path.isfile(os.path.join(dirname,file)) and not os.path.isfile(os.path.join(dirnameB,file)):
if not os.path.isdir(dirnameC):
os.system("mkdir %s"%(dirnameC))
shutil.copy2(os.path.join(dirname,file), os.path.join(dirnameC,file))
elif os.path.isdir(os.path.join(dirname,file)) and not os.path.isdir(os.path.join(dirnameB,file)):
if not os.path.isdir(os.path.join(dirnameC,file)):
os.system("mkdir %s"%(os.path.join(dirnameC,file)))
else:
#若pathB裡不存在對應的資料夾,則在pathC裡建立對應的資料夾並複製檔案
if not os.path.isdir(dirnameC):
os.system("mkdir %s"%(dirnameC))

for file in names:
shutil.copy2(os.path.join(dirname,file), os.path.join(dirnameC,file))

#============================================================


if __name__=="__main__":
#這一行程式碼呼叫前面的visit函式,進行檔案查詢並遞迴處理
walk(PathA, visit, 0)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9697/viewspace-1011813/,如需轉載,請註明出處,否則將追究法律責任。

相關文章