用python批量移动文件
我是用来移动图片的,其他格式的文档也是可以的,改下后缀列表就可以了
importos,shutil importdatetime #将文件夹里的图片全部移动到新文件夹中 #revisedbyStephenShen2020-3-1009:28:50 defrenameFile(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) returndstpath defmoveFile(oldpath,newpath): ifos.path.exists(newpath): newpath=renameFile(newpath) try: shutil.move(oldpath,newpath) print(oldpath+'ismoved') except: print(oldpath+'isskipped') 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') ifnotos.path.exists(outpath): os.makedirs(outpath) ifnotos.path.exists(image_outpath): os.makedirs(image_outpath) ifnotos.path.exists(doc_outpath): os.makedirs(doc_outpath) ifnotos.path.exists(emf_outpath): os.makedirs(emf_outpath) ifnotos.path.exists(wmf_outpath): os.makedirs(wmf_outpath) forfolder,subfolders,filesinos.walk(inpath): forfileinfiles: oldpath=os.path.join(folder,file) ifos.path.splitext(file)[-1]inimage_ext: newpath=os.path.join(image_outpath,file) moveFile(oldpath,newpath) elifos.path.splitext(file)[-1]indoc_ext: newpath=os.path.join(doc_outpath,file) moveFile(oldpath,newpath) elifos.path.splitext(file)[-1]inemf_ext: newpath=os.path.join(emf_outpath,file) moveFile(oldpath,newpath) elifos.path.splitext(file)[-1]inwmf_ext: newpath=os.path.join(wmf_outpath,file) moveFile(oldpath,newpath) else: continue print('done')
然后再删除空文件夹
importos,shutil #将文件夹里的空文件夹删除 #revisedbyStephenShen2020-3-817:50:24 inpath=r'E:\pics-moving\待分类照片' forfolder,subfolders,filesinos.walk(inpath): ifnotos.listdir(folder): shutil.rmtree(folder) #print(folder+'isempyt') print(folder+'isdeleted') print('done')
以上就是用python批量移动文件的详细内容,更多关于python批量移动文件的资料请关注毛票票其它相关文章!