用python实现复制大量文件

本文介绍了一种快速批量复制大量文件的方法,包括连同子目录一起完整复制和仅复制特定格式文件两种策略,通过Python代码实现,大幅提高了数据迁移效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  本来是去项目公司拷数据,结果去了发现有500G,靠系统的复制功能怕是得好几个小时,于是回来学一手操作,话不多说上代码:

说明:CopyFiles1是可以将sourceDir连子目录一起原样复制到targetDir,而CopyFiles2是在sourceDir中筛选特定格式文件,然后将其直接放在targetDir中,会很乱。。。但是很快

import os
import time
import shutil
sourceDir = r"D:\copytest\datatest"
targetDir = r"D:\copytest\result"
copyFileCounts = 0

def CopyFiles1(sourceDir, targetDir):
#完全连子目录也会复制好,美观
   global copyFileCounts
   print(sourceDir )
   print("%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))):

               open(targetF, "wb").write(open(sourceF, "rb").read())
               print ("%s %s 复制完毕" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF))
           else:
               print ("%s %s 已存在,不重复复制" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF))

       if os.path.isdir(sourceF):
           copyFiles(sourceF, targetF)

def CopyFiles2(dir):
    #会将目录下所有文件都复制在一起,速度快,可以筛选文件
    i=0
    for root,dir1,filename in os.walk(dir):
     #print(filename)
     for index in range(len(filename)):
        #print(os.path.splitext(filename[index])[1])
        #if os.path.splitext(filename[index])[1]=='.':#这里注意filename是个元组,splitext方法的时候只能是字符串
        if 1==1:
            #i+=1
            print('here')
            root1="D:\\copytest\\result3"
            old_path = os.path.join(root, filename[index])
            print(old_path)
            new_path = os.path.join(root1,filename[index])
            shutil.copyfile(old_path,new_path)

#print("总共有",i,"图层文件被复制!")

if __name__ == "__main__":
  time_start = time.time()
  try:
    import psyco
    psyco.profile()
  except ImportError:
     pass
  #CopyFiles1(sourceDir,targetDir)
  CopyFiles2("D:/copytest/datatest")
  time_end = time.time()
  print('totally cost', time_end - time_start)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值