您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關利用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怎么批量移動文件就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。