本来是去项目公司拷数据,结果去了发现有500G,靠系统的复制功能怕是得好几个小时,于是回来学一手操作,话不多说上代码: 说明:CopyFiles1是可以将sourceDir连子目录一起原样复制到targetDir,而CopyFiles2是在sourceDir中筛选特定格式文件,然后将其直接放在targetDir中,会很乱。。。但是很快 sourceDir = r'D:\copytest\datatest' targetDir = r'D:\copytest\result' def CopyFiles1(sourceDir, targetDir): 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): 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)) print ('%s %s 已存在,不重复复制' %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)) if os.path.isdir(sourceF): copyFiles(sourceF, targetF) #会将目录下所有文件都复制在一起,速度快,可以筛选文件 for root,dir1,filename in os.walk(dir): for index in range(len(filename)): #print(os.path.splitext(filename[index])[1]) #if os.path.splitext(filename[index])[1]=='.':#这里注意filename是个元组,splitext方法的时候只能是字符串 root1='D:\\copytest\\result3' old_path = os.path.join(root, filename[index]) new_path = os.path.join(root1,filename[index]) shutil.copyfile(old_path,new_path) #print('总共有',i,'图层文件被复制!') if __name__ == '__main__': #CopyFiles1(sourceDir,targetDir) CopyFiles2('D:/copytest/datatest') print('totally cost', time_end - time_start)
|