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

本文实例为大家分享了python实现复制大量文件的具体代码,供大家参考,具体内容如下:
说明:CopyFiles1是可以将sourceDir连子目录一起原样复制到targetDir,而CopyFiles2是在sourceDir中筛选特定格式文件,然后将其直接放在targetDir中,会很乱,但是很快
1 import os2 import time3 import shutil4 sourceDir = r"D:copytestdatatest"5 targetDir = r"D:copytestesult"6 copyFileCounts = 07 8 def CopyFiles1(sourceDir, targetDir):9 #完全连子目录也会复制好,美观10 global copyFileCounts11 print(sourceDir )12 print("%s 当前处理文件夹%s已处理%s 个文件" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), sourceDir,copyFileCounts) )13 for f in os.listdir(sourceDir):14 sourceF = os.path.join(sourceDir, f)15 targetF = os.path.join(targetDir, f)16 17 if os.path.isfile(sourceF):18 19 if not os.path.exists(targetDir):20 os.makedirs(targetDir)21 copyFileCounts += 122 23 24 if not os.path.exists(targetF) or (os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))):25 26 open(targetF, "wb").write(open(sourceF, "rb").read())27 print ("%s %s 复制完毕" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF))28 else:29 print ("%s %s 已存在,不重复复制" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF))30 31 if os.path.isdir(sourceF):32 copyFiles(sourceF, targetF)33 34 def CopyFiles2(dir):35 #会将目录下所有文件都复制在一起,速度快,可以筛选文件36 i=037 for root,dir1,filename in os.walk(dir):38 #print(filename)39 for index in range(len(filename)):40 #print(os.path.splitext(filename[index])[1])41 #if os.path.splitext(filename[index])[1]=='.':#这里注意filename是个元组,splitext方法的时候只能是字符串42 if 1==1:43 #i+=144 print('here')45 root1="D:copytestesult3"46 old_path = os.path.join(root, filename[index])47 print(old_path)48 new_path = os.path.join(root1,filename[index])49 shutil.copyfile(old_path,new_path)50 51 #print("总共有
本文介绍了一种使用Python快速复制大量文件的方法。通过两个函数CopyFiles1和CopyFiles2,前者能完整复制文件夹及其子目录,后者则快速复制特定格式的文件至目标文件夹。该方法适用于需要高效处理大规模数据复制的场景。
5128

被折叠的 条评论
为什么被折叠?



