如下所示:
import osimport timefrom collections import deque"""利用遞歸實(shí)現(xiàn)目錄的遍歷@para sourcePath:原文件目錄@para targetPath:目標(biāo)文件目錄"""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): #拼接原文件或者文件夾的絕對(duì)路徑 absourcePath = os.path.join(sourcePath, fileName) #拼接目標(biāo)文件或者文件加的絕對(duì)路徑 abstargetPath = os.path.join(targetPath, fileName) #判斷原文件的絕對(duì)路徑是目錄還是文件 if os.path.isdir(absourcePath): #是目錄就創(chuàng)建相應(yīng)的目標(biāo)目錄 os.makedirs(abstargetPath) #遞歸調(diào)用getDirAndCopyFile()函數(shù) getDirAndCopyFile(absourcePath,abstargetPath) #是文件就進(jìn)行復(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) #時(shí)間是用來(lái)計(jì)算復(fù)制總共消耗了多少時(shí)間 endTime = time.clock() time_mi = endTime // 60 time_s = endTime // 1 % 60 time_ms = ((endTime * 100) // 1) % 100 print("總用時(shí):%02.0f:%02.0f:%2.0f" % (time_mi, time_s, time_ms))
以上這篇Python利用遞歸實(shí)現(xiàn)文件的復(fù)制方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選