python 实现目录下迭代copy

闲话少说,直接上菜:

#!/usr/bin/env python
# -*-coding=utf8

import os
import time

sourceDir='/usr/local/src/test1'
targetDir='/usr/local/src/test2'
copyFileCounts=0

def copyFiles(sourceDir,targetDir):
  global copyFileCounts
  print sourceDir
  print u"%s当前处理文件夹%s已处理%s个文件"%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),sourceDir,copyFileCounts)
  for f in os.listdir(sourceDir):
    sourceF=os.path.join(sourceDir,f)
    print sourceF
    targetF=os.path.join(targetDir,f)
    print targetF
  
    if os.path.isfile(sourceF):
      #创建目录
      if not os.path.exists(targetDir):
        os.makedirs(targetDir)
      copyFileCounts += 1
      #文件不存在,或者存在但是大小不一样,覆盖
      if not os.path.exists(targetF) or (os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))):
        #2进制文件
        open(targetF,"wb").write(open(sourceF,"rb").read())
        print u"%s%s复制完毕"%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),targetF)
      else:
        print u"%s%s已存在,不重复复制"%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),targetF)
    if os.path.isdir(sourceF):
      copyFiles(sourceF,targetF)

if __name__=="__main__":
  try:
    import psyco
    psyco.profile()
  except ImportError:
    pass
  copyFiles(sourceDir,targetDir)

判断文件是否相同可以改为对比MD5

你可能感兴趣的:(python,local,文件夹)