溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python利用遞歸實現(xiàn)文件的復(fù)制方法

發(fā)布時間:2020-09-05 07:43:14 來源:腳本之家 閱讀:178 作者:左邊Luckyboy 欄目:開發(fā)技術(shù)

如下所示:

import os
import time
from 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)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI