如下所示:
import osimport timefrom collections import deque"""利用遞歸實現(xiàn)目錄的遍歷@para sourcePath:原文件目錄@para targetPath:目標文件目錄"""def getDirAndCopyFile(sourcePath,targetPath): if not os.path.exists(sourcePath): return if not os.path.exists(targetPath): os.makedirs(targetPath) #遍歷文件夾 for fileName in os.listdir(sourcePath): #拼接原文件或者文件夾的絕對路徑 absourcePath = os.path.join(sourcePath, fileName) #拼接目標文件或者文件加的絕對路徑 abstargetPath = os.path.join(targetPath, fileName) #判斷原文件的絕對路徑是目錄還是文件 if os.path.isdir(absourcePath): #是目錄就創(chuàng)建相應(yīng)的目標目錄 os.makedirs(abstargetPath) #遞歸調(diào)用getDirAndCopyFile()函數(shù) getDirAndCopyFile(absourcePath,abstargetPath) #是文件就進行復(fù)制 if os.path.isfile(absourcePath): rbf = open(absourcePath,"rb") wbf = open(abstargetPath,"wb") while True: content = rbf.readline(1024*1024) if len(content)==0: break wbf.write(content) wbf.flush() rbf.close() wbf.close()if __name__ == '__main__': startTime = time.clock() sourcePath = r"H:/培訓(xùn)資料" targetPath = r"H:/培訓(xùn)資料_備份" getDirAndCopyFile(sourcePath,targetPath) #時間是用來計算復(fù)制總共消耗了多少時間 endTime = time.clock() time_mi = endTime // 60 time_s = endTime // 1 % 60 time_ms = ((endTime * 100) // 1) % 100 print("總用時:%02.0f:%02.0f:%2.0f" % (time_mi, time_s, time_ms))
以上這篇Python利用遞歸實現(xiàn)文件的復(fù)制方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答