1. 程式人生 > 程式設計 >python實現複製大量檔案功能

python實現複製大量檔案功能

本文例項為大家分享了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',targetF))
      else:
        print ("%s %s 已存在,不重複複製" %(time.strftime('%Y-%m-%d %H:%M:%S',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)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。