小编给大家分享一下python如何实现复制大量文件功能,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
说明: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如何实现复制大量文件功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。