您的位置:首页 > 编程语言 > Python开发

python实现复制大量文件功能

2019-08-31 11:50 751 查看

本文实例为大家分享了python实现复制大量文件的具体代码,供大家参考,具体内容如下

本来是去项目公司拷数据,结果去了发现有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)

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 复制文件