Python uses recursion to implement the file copy method

  • 2021-01-06 00:39:35
  • OfStack

As shown below:


import os
import time
from collections import deque

"""
 Recursion is used to traverse the directory 
@para sourcePath: Original file directory 
@para targetPath: Destination file directory 
"""
def getDirAndCopyFile(sourcePath,targetPath):

  if not os.path.exists(sourcePath):
    return
  if not os.path.exists(targetPath):
    os.makedirs(targetPath)
    
  # Traverse folder 
  for fileName in os.listdir(sourcePath):
    # The absolute path to concatenate the original file or folder 
    absourcePath = os.path.join(sourcePath, fileName)
    # Splice the absolute path to the target file or file addition 
    abstargetPath = os.path.join(targetPath, fileName)
    # Determine whether the absolute path to the original file is a directory or a file 
    if os.path.isdir(absourcePath):
      # Is a directory to create the corresponding target directory 
      os.makedirs(abstargetPath)
      # Recursive calls getDirAndCopyFile() function 
      getDirAndCopyFile(absourcePath,abstargetPath)
    # Copy the file as it is 
    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:\ Training materials "
  targetPath = r"H:\ Training materials _ The backup "
  getDirAndCopyFile(sourcePath,targetPath)
  # Time is used to calculate the total amount of time consumed by replication 
  endTime = time.clock()
  time_mi = endTime // 60
  time_s = endTime // 1 % 60
  time_ms = ((endTime * 100) // 1) % 100
  print(" The total available :%02.0f:%02.0f:%2.0f" % (time_mi, time_s, time_ms))

Related articles: