欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python如何实现复制目录到指定目录

时间:2021-06-16 08:22:03|栏目:Python代码|点击:

本文实例为大家分享了python复制目录到指定目录的具体代码,供大家参考,具体内容如下

保存下面代码为一个文件直接运行

import os
import time
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)
  targetF = os.path.join(targetDir, f)
  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__":
 copyFiles('/content/chest_xray/', '/content/drive/My Drive/chest_xray/')

删除非空目录的所有有文件,包含目录本身

import shutil
shutil.rmtree('D:/content/')

上一篇:深入学习python多线程与GIL

栏    目:Python代码

下一篇:手把手教你从PyCharm安装到激活(最新激活码),亲测有效可激活至2089年

本文标题:python如何实现复制目录到指定目录

本文地址:http://www.codeinn.net/misctech/142805.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有