Python高效批量复制大量文件:两种策略与代码实现

Oliver
Oliver
发布时间:2026-10-13 | 4人浏览过
原创

本文介绍使用Python处理500GB级别大量文件复制的两种方法。CopyFiles1保留目录结构,适合整理归档;CopyFiles2扁平化输出特定格式文件,速度更快但目录混乱。通过对比两种策略的代码实现与性能差异,帮助开发者根据实际需求选择合适的大规模文件复制方案。

本文分享利用Python脚本实现高效批量复制大量文件的完整代码示例,供读者参考与学习。

Python批量复制大量文件背景与需求

起初计划前往项目公司拷贝数据,发现数据总量高达500GB。若依赖操作系统自带的复制功能,预计耗时数小时。为此,笔者专门研究并编写了相应的处理脚本,以下直接展示核心代码:

代码包含两个主要函数:CopyFiles1负责将源目录(sourceDir)及其所有子目录结构完整镜像复制到目标目录(targetDir),保持原有层级关系,视觉效果整洁;CopyFiles2则用于从源目录中筛选特定格式的文件,并直接放置到目标目录顶层,虽然会导致文件存放杂乱,但处理速度显著提升。

两种复制策略的代码实现


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)

总结与展望

上述内容即为本文的全部分享,希望能为读者的技术学习提供有益帮助,同时也欢迎读者继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表