天天看點

拷貝資料幾小時?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,784758214
群裡有不錯的學習視訊教程、開發工具與電子書籍。
與你分享python企業當下人才需求及怎麼從零基礎學習好python,和學習什麼内容
           

以上就是本文的全部内容,覺得文章還不錯的話不妨收藏起來慢慢看,有任何建議或看法歡迎大家在評論區分享讨論!