利用python怎么批量移动文件-创新互联
这篇文章将为大家详细讲解有关利用python怎么批量移动文件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
目前创新互联已为上千家的企业提供了网站建设、域名、网站空间、网站托管运营、企业网站设计、南丹网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。import os,shutil import datetime #将文件夹里的图片全部移动到新文件夹中 #revised by Stephen Shen 2020-3-10 09:28:50 def renameFile(dstpath): fdirname,fbasename=os.path.split(dstpath) #文件名相同但大小不同 fname,fext=os.path.splitext(fbasename) nowtime=datetime.datetime.now() strtime=str(nowtime.year)+str(nowtime.month)+str(nowtime.day)+str(nowtime.hour)+str(nowtime.minute) newfbasename=fname+'-'+strtime+fext dstpath=os.path.join(fdirname,newfbasename) return dstpath def moveFile(oldpath,newpath): if os.path.exists(newpath): newpath=renameFile(newpath) try: shutil.move(oldpath,newpath) print(oldpath+' is moved') except: print(oldpath+' is skipped') inpath=r'K:\fileExtracted\imagesFromDocs' outpath=r'K:\filesExtracted' image_ext=['.JPG','.jpg','.png','.PNG','.jpeg','.wdp'] image_outpath=os.path.join(outpath,'image') doc_ext=['.doc','.docx'] doc_outpath=os.path.join(outpath,'doc') emf_ext=['.emf'] emf_outpath=os.path.join(image_outpath,'emf') wmf_ext=['.wmf'] wmf_outpath=os.path.join(image_outpath,'wmf') if not os.path.exists(outpath): os.makedirs(outpath) if not os.path.exists(image_outpath): os.makedirs(image_outpath) if not os.path.exists(doc_outpath): os.makedirs(doc_outpath) if not os.path.exists(emf_outpath): os.makedirs(emf_outpath) if not os.path.exists(wmf_outpath): os.makedirs(wmf_outpath) for folder,subfolders,files in os.walk(inpath): for file in files: oldpath=os.path.join(folder,file) if os.path.splitext(file)[-1] in image_ext: newpath=os.path.join(image_outpath,file) moveFile(oldpath,newpath) elif os.path.splitext(file)[-1] in doc_ext: newpath=os.path.join(doc_outpath,file) moveFile(oldpath,newpath) elif os.path.splitext(file)[-1] in emf_ext: newpath=os.path.join(emf_outpath,file) moveFile(oldpath,newpath) elif os.path.splitext(file)[-1] in wmf_ext: newpath=os.path.join(wmf_outpath,file) moveFile(oldpath,newpath) else: continue print('done')
然后再删除空文件夹
import os,shutil #将文件夹里的空文件夹删除 #revised by Stephen Shen 2020-3-8 17:50:24 inpath=r'E:\pics-moving\待分类照片' for folder,subfolders,files in os.walk(inpath): if not os.listdir(folder): shutil.rmtree(folder) # print(folder+' is empyt') print(folder+' is deleted') print('done')
关于利用python怎么批量移动文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
新闻标题:利用python怎么批量移动文件-创新互联
路径分享:http://cdiso.cn/article/dddsoe.html