python实现将多个文件分配到多个文件夹的方法
如下所示:
importos importshutil #pathofimgr path='D:\\BaiduNetdiskDownload\\newim\\' #pathoffolder folderPath='D:\\BaiduNetdiskDownload\\folderSort\\' peopleNumber=61 #new61foldernumbersassort_folder_number[61] sort_folder_number=[xforxinrange(0,peopleNumber)] #makedir61folders ''' demo功能说明: 在folderPath处新建60个文件夹, 图片存储在path处 给每个文件夹分配150张图片(将9000张图片平均分配到60个文件夹) Tips: 1:os.path.join(path1,path2...) thisfunctionisusedtocombinethepath,itreturnsapathwhichis'path1/path2...' 2:os.makedirs(path) thisfunctionisusedtomakeadirectory(newfolder)inthepathparam 3:shutil.move(oldPath,newPath) thisfunctionisusedtomovefilefromparam1toparam2 4:os.path.exists(path) thisfunctionisusedtocheckthefilePath(param1)whetherexists ''' fornumberinsort_folder_number: new_folder_path=os.path.join(folderPath,'%s'%number)#new_folder_pathis‘folderPath\number' ifnotos.path.exists(new_folder_path): os.makedirs(new_folder_path) print("newaflodernamed"+str(number)+'atthepathof'+new_folder_path) #givetheimglist file_list=os.listdir(path) '''definethefirstfoloderNumber''' folderNumber=1 print('thereare'+str(len(file_list))+'filesatthepathof'+path) foriinrange(0,len(file_list)): old_file_path=os.path.join(path,str(i)+'.jpg') ifos.path.isdir(old_file_path): '''ifthepathisafolder,programwillpassit''' print('imgdoesnotexist,path='+old_file_path+'itisadir') pass elifnotos.path.exists(old_file_path): '''ifthepathdoesnotexist,programwillpassit''' print('imgdoesnotexist,path='+old_file_path) pass else: '''definethenumber,itdecideshowmanyimgseachpeopleprocess''' number=150#int(len(file_list)/peopleNumber) if(i%number==0): folderNumber+=1 new_file_path=os.path.join(folderPath,'%s'%(folderNumber)) ifnotos.path.exists(new_file_path): print('notexistpath:'+new_file_path) break shutil.move(old_file_path,new_file_path) print('successmovefilefrom'+old_file_path+'to'+new_file_path)
以上这篇python实现将多个文件分配到多个文件夹的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。