当前位置: 移动技术网 > IT编程>脚本编程>Python > python实现复制大量文件功能

python实现复制大量文件功能

2019年09月06日  | 移动技术网IT编程  | 我要评论

娃娃王妃采草记,91pore,尼采s600

本文实例为大家分享了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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网