python实现将多个文件分配到多个文件夹的方法

yipeiwu_com5年前Python基础

如下所示:

import os
import shutil

#path of imgr
path = 'D:\\BaiduNetdiskDownload\\newim\\'

#path of folder
folderPath = 'D:\\BaiduNetdiskDownload\\folderSort\\'

peopleNumber = 61
#new 61 folder numbers as sort_folder_number[61]
sort_folder_number = [x for x in range(0,peopleNumber)]

# makedir 61 folders
'''
demo功能说明:
在folderPath处新建60个文件夹,
图片存储在path处
给每个文件夹分配150张图片(将9000张图片平均分配到60个文件夹)

Tips:
1: os.path.join(path1,path2...)
this function is used to combine the path,it returns a path which is 'path1/path2...'

2: os.makedirs(path)
this function is used to make a directory(new folder) in the path param

3: shutil.move(oldPath,newPath)
this function is used to move file from param1 to param 2

4: os.path.exists(path)
this function is used to check the filePath(param1) whether exists
'''
for number in sort_folder_number:
 new_folder_path = os.path.join(folderPath,'%s'%number)#new_folder_path is ‘folderPath\number'

 if not os.path.exists(new_folder_path):
  os.makedirs(new_folder_path)
  print("new a floder named "+str(number)+'at the path of '+ new_folder_path)

#give the img list
file_list = os.listdir(path)

'''define the first foloderNumber'''
folderNumber = 1
print('there are '+str(len(file_list))+' files at the path of '+path)
for i in range(0,len(file_list)):
 old_file_path = os.path.join(path,str(i)+'.jpg')
 if os.path.isdir(old_file_path):
  '''if the path is a folder,program will pass it'''
  print('img does not exist ,path=' + old_file_path+' it is a dir' )
  pass
 elif not os.path.exists(old_file_path):
  '''if the path does not exist,program will pass it'''
  print('img does not exist ,path='+old_file_path)
  pass
 else:
  '''define the number,it decides how many imgs each people process'''
  number = 150 #int(len(file_list)/peopleNumber)
  if(i%number ==0):
   folderNumber +=1
  new_file_path = os.path.join(folderPath,'%s'%(folderNumber))
  if not os.path.exists(new_file_path):
   print('not exist path:'+new_file_path)
   break
  shutil.move(old_file_path,new_file_path)
  print('success move file from '+ old_file_path +' to '+new_file_path)

以上这篇python实现将多个文件分配到多个文件夹的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python opencv如何实现图片绘制

python opencv如何实现图片绘制

这篇文章主要介绍了python opencv如何实现图片绘制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 点和圆 : circle...

windows下安装python paramiko模块的代码

1.安装python  windows版本好:python-2.5.1.msi2.安装pycrypto windows版本号:pycrypto-2.0.1.win32-py2....

简介二分查找算法与相关的Python实现示例

二分查找Binary Search的思想: 以有序表表示静态查找表时,查找函数可以用二分查找来实现。 二分查找(Binary Search)的查找过程是:先确定待查记录所在的区间,然后逐...

Python基于OpenCV库Adaboost实现人脸识别功能详解

Python基于OpenCV库Adaboost实现人脸识别功能详解

本文实例讲述了Python基于OpenCV库Adaboost实现人脸识别功能。分享给大家供大家参考,具体如下: 以前用Matlab写神经网络的面部眼镜识别算法,研究算法逻辑,采集大量训练...

线程安全及Python中的GIL原理分析

本文讲述了线程安全及Python中的GIL。分享给大家供大家参考,具体如下: 摘要 什么是线程安全? 为什么python会使用GIL的机制? 在多核时代的到来的背景下,...