拷贝数据几小时?python63行代码轻松复制500G文件

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

《拷贝数据几小时?python63行代码轻松复制500G文件》

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

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

1 import os
2 import time
3 import shutil
4 sourceDir = r"D:\copytest\datatest"
5 targetDir = r"D:\copytest\result"
6 copyFileCounts = 0
7 
8 def CopyFiles1(sourceDir, targetDir):
9 #完全连子目录也会复制好,美观
10 global copyFileCounts
11 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 += 1
22 
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=0
37 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+=1
44 print('here')
45 root1="D:\\copytest\\result3"
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("总共有",i,"图层文件被复制!")
52 
53 if __name__ == "__main__":
54 time_start = time.time()
55 try:
56 import psyco
57 psyco.profile()
58 except ImportError:
59 pass
60 #CopyFiles1(sourceDir,targetDir)
61 CopyFiles2("D:/copytest/datatest")
62 time_end = time.time()
63 print('totally cost', time_end - time_start)
在学习过程中有什么不懂得可以加我的
python学习交流扣扣qun,×××
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容

以上就是本文的全部内容,觉得文章还不错的话不妨收藏起来慢慢看,有任何建议或看法欢迎大家在评论区分享讨论!

    原文作者:刘智民
    原文地址: https://blog.51cto.com/14568144/2444592
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞